package jnormaliz;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.jdesktop.application.Action;
import org.jdesktop.application.Application;

/**
 * Dialog for creating a new input file, together with all its actions
 */
public class NewFileDialog extends javax.swing.JDialog  {

    private final JFileChooser fileChooser;
    private final MainView mainView;
    
    private File selectedFile = null;

    /** Creates new form NewFileDialog */
    public NewFileDialog(MainView parent, boolean modal) {
        super(parent.getFrame(), modal);
        initComponents();

        this.setIconImage(
                Application.getInstance(Application.class).getContext().
                getResourceMap(NewFileDialog.class).
                getImageIcon("Application.icon").getImage());
        
        mainView = parent;

        // Initializes file chooser
        fileChooser = new JFileChooser((File) null);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setFileFilter(MainView.inputFileFilter);
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.setApproveButtonText("Select");
        fileChooser.setDialogTitle("New input file");
    }

    /** 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        fileTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        modeComboBox = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        rowsFormattedTextField = new javax.swing.JFormattedTextField();
        columnsFormattedTextField = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        folderTextArea = new javax.swing.JTextArea();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(jnormaliz.JNormalizApplication.class).getContext().getResourceMap(NewFileDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setIconImage(null);
        setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
        setName("Form"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(jnormaliz.JNormalizApplication.class).getContext().getActionMap(NewFileDialog.class, this);
        jButton1.setAction(actionMap.get("chooseFolderAction")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setDefaultCapable(false);
        jButton1.setFocusCycleRoot(true);
        jButton1.setName("jButton1"); // NOI18N

        jButton2.setAction(actionMap.get("okAction")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        jButton3.setAction(actionMap.get("cancelAction")); // NOI18N
        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setDefaultCapable(false);
        jButton3.setName("jButton3"); // NOI18N

        fileTextField.setEditable(false);
        fileTextField.setText(resourceMap.getString("fileTextField.text")); // NOI18N
        fileTextField.setName("fileTextField"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        modeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Integral closure", "Normalization", "Polytope", "Rees algebra", "Hyperplanes", "Equations", "Congruences", "Lattice ideal" }));
        modeComboBox.setName("modeComboBox"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        rowsFormattedTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        rowsFormattedTextField.setText(resourceMap.getString("rowsFormattedTextField.text")); // NOI18N
        rowsFormattedTextField.setName("rowsFormattedTextField"); // NOI18N

        columnsFormattedTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        columnsFormattedTextField.setText(resourceMap.getString("columnsFormattedTextField.text")); // NOI18N
        columnsFormattedTextField.setName("columnsFormattedTextField"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        folderTextArea.setBackground(getBackground());
        folderTextArea.setColumns(20);
        folderTextArea.setEditable(false);
        folderTextArea.setFont(getFont());
        folderTextArea.setRows(1);
        folderTextArea.setName("folderTextArea"); // NOI18N
        jScrollPane1.setViewportView(folderTextArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 457, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(columnsFormattedTextField, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(rowsFormattedTextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(modeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel5)))
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fileTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fileTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(11, 11, 11)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(modeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(rowsFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(columnsFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFormattedTextField columnsFormattedTextField;
    private javax.swing.JTextField fileTextField;
    private javax.swing.JTextArea folderTextArea;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox modeComboBox;
    private javax.swing.JFormattedTextField rowsFormattedTextField;
    // End of variables declaration//GEN-END:variables

    void showDialog(File lastDirectoryUsed) {
        selectedFile = new File(lastDirectoryUsed,"untitled.in");

        fileTextField.setText(selectedFile.getName());
        folderTextArea.setText(selectedFile.getParent());
        rowsFormattedTextField.setText("");
        columnsFormattedTextField.setText("");
        setLocationRelativeTo(getParent());
        setVisible(true);
    }

    @Action
    public void chooseFolderAction() {
        fileChooser.setSelectedFile(selectedFile);

        int result = fileChooser.showOpenDialog(this);

        if (result == JFileChooser.APPROVE_OPTION) {

            final File chosenFile = fileChooser.getSelectedFile();

            if(!chosenFile.getName().endsWith(".in")) {
                JOptionPane.showMessageDialog(this,
                        "Input files should have .in extension", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            selectedFile = chosenFile;
            fileTextField.setText(selectedFile.getName());
            folderTextArea.setText(selectedFile.getParent());
        }
    }

    @Action
    public void okAction() {

        int rows;
        int columns;

        // Checks validity of data

        rows = Integer.parseInt(rowsFormattedTextField.getText());

        if (rows < 1) {
            JOptionPane.showMessageDialog(this,
                    "'Rows' should be a positive integer", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        columns = Integer.parseInt(columnsFormattedTextField.getText());

        if (columns < 1) {
            JOptionPane.showMessageDialog(this,
                    "'Columns' should be a positive integer", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (selectedFile.exists()) {
            int result = JOptionPane.showConfirmDialog(this,
                    "File exists. Overwrite it?",
                    "Attention",
                    JOptionPane.WARNING_MESSAGE);

            if (result != JOptionPane.OK_OPTION) {
                return;
            }
        }
        try {
            PrintWriter printWriter = new PrintWriter(selectedFile);

            printWriter.println(rows);
            printWriter.println(columns);

            for (int i = 0; i < rows; i++) {
                boolean firstColumn = true;
                for (int j = 0; j < columns; j++) {
                    if (firstColumn) {
                        printWriter.print("0");
                        firstColumn = false;
                    } else {
                        printWriter.print(" 0");
                    }
                }
                printWriter.print("\r");
            }

            switch( modeComboBox.getSelectedIndex()){

                case 0:
                    printWriter.println("integral_closure\r");
                    break;

                case 1:
                    printWriter.println("normalization\r");
                    break;

                case 2:
                    printWriter.println("polytope\r");
                    break;

                case 3:
                    printWriter.println("rees_algebra\r");
                    break;

                case 4:
                    printWriter.println("hyperplanes\r");
                    break;

                case 5:
                    printWriter.println("equations\r");
                    break;

                case 6:
                    printWriter.println("congruences\r");
                    break;

                case 7:
                    printWriter.println("lattice_ideal\r");
                    break;


            }

           // printWriter.println(modeComboBox.getSelectedIndex());

            printWriter.close();

            if (mainView.loadInputFile(selectedFile)) {
                mainView.setInputFile(null);
                mainView.setInputFile(selectedFile);
            }

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this,
                    "Unable to create file:\n" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(NewFileDialog.class.getName()).log(Level.SEVERE, null, ex);
        }

        setVisible(false);
    }

    @Action
    public void cancelAction() {
        this.setVisible(false);
    }
}
