/* 
 * Copyright (C) 2017 Laboratory of Experimental Biophysics
 * Ecole Polytechnique Federale de Lausanne
 * 
 * Author: Marcel Stefko
 * 
 * This program 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.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ch.epfl.leb.sass.ijplugin;

import ch.epfl.leb.sass.simulator.generators.realtime.STORMsim;
import ij.IJ;
import ij.ImagePlus;
import ij.plugin.frame.PlugInFrame;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.IOException;

/**
 * Main FIJI plugin frame.
 * @author Marcel Stefko
 */
public class GUI extends PlugInFrame {
    App app;
    /**
     * Creates new form MainFrame
     * @param title title of the window
     */
    public GUI(String title) {
        super(title);
        initComponents();
    }
    
    /**
     * Initialize the new frame
     */
    public GUI() {
        super("SASS - SMLM Acquisition Simulation Software");
        setSize(200, 200);
        initComponents();
        setVisible(true);
        InitializeSimulation f = new InitializeSimulation(null, false, this);
        f.setVisible(true);

        
    }
    
    /**
     * Show the frame and initialize backend.
     * @param arg
     */
    @Override
    public void run(String arg) {
        
    }
    
    /**
     * Set the App which this GUI should control
     * @param app
     */
    public void setApp(App app) {
        this.app = app;
    }



    /**
     * 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() {

        setpointEntry = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        savePositions = new javax.swing.JButton();
        saveTransitions = new javax.swing.JButton();
        startSimButton = new javax.swing.JButton();
        stopSimButton = new javax.swing.JToggleButton();
        jSeparator1 = new javax.swing.JSeparator();

        setMinimumSize(new java.awt.Dimension(260, 180));
        setTitle("STORMsim");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        setpointEntry.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        setpointEntry.setText("1");

        jLabel1.setText("Controller setpoint");

        savePositions.setText("Save positions...");
        savePositions.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                savePositionsActionPerformed(evt);
            }
        });

        saveTransitions.setText("Save transitions...");
        saveTransitions.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveTransitionsActionPerformed(evt);
            }
        });

        startSimButton.setText("Start");
        startSimButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startSimButtonActionPerformed(evt);
            }
        });

        stopSimButton.setText("Stop");
        stopSimButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopSimButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, 0)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(savePositions, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(saveTransitions))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(startSimButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(stopSimButton, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(setpointEntry, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {startSimButton, stopSimButton});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {savePositions, saveTransitions});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(setpointEntry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(startSimButton)
                    .addComponent(stopSimButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(savePositions)
                    .addComponent(saveTransitions))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Exit the plugin
     */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        //System.exit(0);
    }//GEN-LAST:event_exitForm

    private void savePositionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_savePositionsActionPerformed
        JFileChooser fc = new JFileChooser();
        int returnVal;
        fc.setDialogType(JFileChooser.SAVE_DIALOG);
        //set a default filename 
        fc.setSelectedFile(new File("emitter_positions.csv"));
        //Set an extension filter
        fc.setFileFilter(new FileNameExtensionFilter("CSV file","csv"));
        returnVal = fc.showSaveDialog(null);
        if  (returnVal != JFileChooser.APPROVE_OPTION) {
            return;
        }
        File positionsCSVFile = fc.getSelectedFile();
        String filename = positionsCSVFile.getAbsolutePath();
        try {
            app.getPositionLogger().setFilename(filename);
            app.getPositionLogger().saveLogFile();
        } catch (IOException ex) {
            IJ.error("Could not save file: " + filename);
        }
    }//GEN-LAST:event_savePositionsActionPerformed

    private void saveTransitionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveTransitionsActionPerformed
JFileChooser fc = new JFileChooser();
        int returnVal;
        fc.setDialogType(JFileChooser.SAVE_DIALOG);
        //set a default filename 
        fc.setSelectedFile(new File("state_transitions.csv"));
        //Set an extension filter
        fc.setFileFilter(new FileNameExtensionFilter("CSV file","csv"));
        returnVal = fc.showSaveDialog(null);
        if  (returnVal != JFileChooser.APPROVE_OPTION) {
            return;
        }
        File stateCSVFile = fc.getSelectedFile();
        String filename = stateCSVFile.getAbsolutePath();
        try {
            app.getStateLogger().setFilename(filename);
            app.getStateLogger().saveLogFile();
        } catch (IOException ex) {
            IJ.error("Could not save file: " + filename);
        }    }//GEN-LAST:event_saveTransitionsActionPerformed

    private void startSimButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startSimButtonActionPerformed
        try {
            app.setSetpoint(Double.parseDouble(setpointEntry.getText()));
            app.startSimulating();
        } catch (RuntimeException ex) {
            IJ.showMessage("Error in simulation start.", ex.getMessage());
            stopSimButton.setEnabled(true);
            return;
        }
        startSimButton.setEnabled(false);
        stopSimButton.setEnabled(true);
        setpointEntry.setEnabled(false);
    }//GEN-LAST:event_startSimButtonActionPerformed

    private void stopSimButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopSimButtonActionPerformed
        try {
            app.stopSimulating();
        } catch (RuntimeException ex) {
            IJ.showMessage("Error in simulation stop.", ex.getMessage());
            startSimButton.setEnabled(true);
            return;
        }
        
        startSimButton.setEnabled(true);
        stopSimButton.setEnabled(false);
        setpointEntry.setEnabled(true);
    }//GEN-LAST:event_stopSimButtonActionPerformed



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton savePositions;
    private javax.swing.JButton saveTransitions;
    private javax.swing.JTextField setpointEntry;
    private javax.swing.JButton startSimButton;
    private javax.swing.JToggleButton stopSimButton;
    // End of variables declaration//GEN-END:variables
}