/*
 * ExportToTex.java
 *
 * Created on 19 april 2007, 16:47
 *
 * This file is part of SimpLie.
 * 
 * SimpLie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * SimpLie is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with SimpLie.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package edu.simplie.ui;

import edu.simplie.*;

import edu.simplie.algebra.Algebra;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.filechooser.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import edu.simplie.ui.reusable.UIPrintableColorTable;


/**
 * User interface for exporting various things (Dynkin diagram,
 * output of level decomposition) to LaTeX.
 * 
 * @author  Teake Nutma
 * @version $Revision$, $Date$
 */
public class ExportToTex extends javax.swing.JPanel
{
	private AlgebraComposite algebras;
	private FileFilter texFilter;
	private JDialog parent;
	private UIPrintableColorTable repTable;
	private Clipboard clipboard;
	
	/** Creates new form ExportToTex */
	public ExportToTex()
	{
		initComponents();
		clipboard = java.awt.Toolkit.getDefaultToolkit().getSystemClipboard();
	}
	
	public void setup(JDialog parent, UIPrintableColorTable repTable, AlgebraComposite algebras)
	{
		this.algebras = algebras;
		this.parent = parent;
		this.repTable = repTable;
		
		Object[] listData = new Object[repTable.getColumnCount()];
		int[] selectedIndeces = new int[repTable.getColumnCount()];
		
		for (int i = 0; i < repTable.getColumnCount(); i++)
		{
			listData[i] = repTable.getColumnName(i);
			selectedIndeces[i] = i;
		}
		columnList.setListData(listData);
		columnList.setSelectedIndices(selectedIndeces);
	}
	
	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        exportToGroup = new javax.swing.ButtonGroup();
        cancel = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        cbCaption = new javax.swing.JCheckBox();
        cbReps = new javax.swing.JCheckBox();
        jLabel1 = new javax.swing.JLabel();
        rbFile = new javax.swing.JRadioButton();
        rbSout = new javax.swing.JRadioButton();
        rbClipboard = new javax.swing.JRadioButton();
        cbCartanMatrix = new javax.swing.JCheckBox();
        comboAlgebras = new javax.swing.JComboBox();
        comboMatrix = new javax.swing.JComboBox();
        tfColumns = new javax.swing.JLabel();
        spinnerColumns = new edu.simplie.ui.reusable.UISpinner();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        columnList = new javax.swing.JList();
        export = new javax.swing.JButton();

        cancel.setText("Cancel");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Settings", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N

        cbCaption.setSelected(true);
        cbCaption.setText("Include captions");
        cbCaption.setMargin(new java.awt.Insets(0, 0, 0, 0));

        cbReps.setSelected(true);
        cbReps.setText("Export representation table");
        cbReps.setMargin(new java.awt.Insets(0, 0, 0, 0));
        cbReps.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbRepsActionPerformed(evt);
            }
        });

        jLabel1.setText("Export to:");

        exportToGroup.add(rbFile);
        rbFile.setText("File");
        rbFile.setMargin(new java.awt.Insets(0, 0, 0, 0));

        exportToGroup.add(rbSout);
        rbSout.setText("System output");
        rbSout.setMargin(new java.awt.Insets(0, 0, 0, 0));

        exportToGroup.add(rbClipboard);
        rbClipboard.setSelected(true);
        rbClipboard.setText("Clipboard");
        rbClipboard.setMargin(new java.awt.Insets(0, 0, 0, 0));

        cbCartanMatrix.setSelected(true);
        cbCartanMatrix.setText("Export Cartan matrix");
        cbCartanMatrix.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbCartanMatrixActionPerformed(evt);
            }
        });

        comboAlgebras.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Full algebra", "Regular subalgebra", "Internal subalgebra" }));

        comboMatrix.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Cartan matrix", "Inverse of Cartan matrix", "Root space metric", "Quadratic form matrix" }));

        tfColumns.setText("extra columns");

        spinnerColumns.setMinValue(0);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbReps)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(spinnerColumns, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tfColumns))
                            .addComponent(cbCaption)))
                    .addComponent(cbCartanMatrix)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(comboAlgebras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(comboMatrix, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(rbFile)
                            .addComponent(rbSout)
                            .addComponent(rbClipboard))))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cbCartanMatrix)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(comboAlgebras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(comboMatrix, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbReps)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbCaption)
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(spinnerColumns, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfColumns))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(rbClipboard)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rbFile)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rbSout)))
                .addGap(94, 94, 94))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Select table columns", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N

        jScrollPane1.setViewportView(columnList);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)
                .addContainerGap())
        );

        export.setText("Export");
        export.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(export)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(export, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
	
	private void cancelActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cancelActionPerformed
	{//GEN-HEADEREND:event_cancelActionPerformed
		parent.setVisible(false);
	}//GEN-LAST:event_cancelActionPerformed
	
	private void exportActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_exportActionPerformed
	{//GEN-HEADEREND:event_exportActionPerformed
		parent.setVisible(false);
		
		String output = new String();
		
		if(cbCartanMatrix.isSelected())
		{
			Algebra algebra;
			switch(comboAlgebras.getSelectedIndex())
			{
				case 2:
					algebra = algebras.intAlgebra;
					break;
				case 1:
					algebra = algebras.subAlgebra;
					break;
				case 0:
				case -1:
				default:
					algebra = algebras.algebra;
					break;
			}
			switch(comboMatrix.getSelectedIndex())
			{
				case 3:
					output += Helper.matrixToTex(algebra.G);
					break;
				case 2:
					output += Helper.matrixToTex(algebra.B);
					break;
				case 1:
					output += Helper.matrixToTex(algebra.invA);
					break;
				case 0:
				case -1:
				default:
					output += Helper.matrixToTex(algebra.A);
					break;
			}
		}
		output += "\n";
		if(cbReps.isSelected())
			output += repTable.toTeX(cbCaption.isSelected(),columnList.getSelectedIndices(),Math.max(0,spinnerColumns.getValue()));
		
		if(rbFile.isSelected())
		{
			JFileChooser chooser = new JFileChooser("");
			chooser.setSelectedFile(new File(algebras.getDynkinDiagramType() + ".tex"));
			chooser.addChoosableFileFilter(texFilter);
			chooser.setDialogTitle("Export to TeX");
			int returnVal = chooser.showSaveDialog(this);
			
			if ( returnVal == JFileChooser.APPROVE_OPTION )
			{
				String fileURL = chooser.getSelectedFile().getAbsolutePath();
				if(!texFilter.accept(chooser.getSelectedFile()))
					fileURL += ".tex";
				// write it out
				FileWriter outputStream = null;
				try
				{
					outputStream = new FileWriter(fileURL);
					outputStream.write(output);
					outputStream.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		if(rbClipboard.isSelected())
		{
			StringSelection outputSelection = new StringSelection(output);
			clipboard.setContents(outputSelection,outputSelection);
		}
		if(rbSout.isSelected())
		{
			System.out.println("%%%%%%%% BEGIN LATEX OUTPUT %%%%%%%%");
			System.out.print(output);
			System.out.println("%%%%%%%%  END LATEX OUTPUT  %%%%%%%%");
		}
	}//GEN-LAST:event_exportActionPerformed

private void cbCartanMatrixActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbCartanMatrixActionPerformed
	boolean enabled = cbCartanMatrix.isSelected();
	comboAlgebras.setEnabled(enabled);
	comboMatrix.setEnabled(enabled);
}//GEN-LAST:event_cbCartanMatrixActionPerformed

private void cbRepsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbRepsActionPerformed
	boolean enabled = cbReps.isSelected();
	cbCaption.setEnabled(enabled);
	spinnerColumns.setEnabled(enabled);
	tfColumns.setEnabled(enabled);
	columnList.setEnabled(enabled);
}//GEN-LAST:event_cbRepsActionPerformed
	
	
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancel;
    private javax.swing.JCheckBox cbCaption;
    private javax.swing.JCheckBox cbCartanMatrix;
    private javax.swing.JCheckBox cbReps;
    private javax.swing.JList columnList;
    private javax.swing.JComboBox comboAlgebras;
    private javax.swing.JComboBox comboMatrix;
    private javax.swing.JButton export;
    private javax.swing.ButtonGroup exportToGroup;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton rbClipboard;
    private javax.swing.JRadioButton rbFile;
    private javax.swing.JRadioButton rbSout;
    private edu.simplie.ui.reusable.UISpinner spinnerColumns;
    private javax.swing.JLabel tfColumns;
    // End of variables declaration//GEN-END:variables
	
}
