/*
 * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved.
 */

import ch.psi.psaf.Task;
import java.awt.Color;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import ch.psi.utils.IO;
import ch.psi.utils.State;
import ch.psi.utils.swing.SwingUtils;
import ch.psi.pshell.data.PlotDescriptor;
import ch.psi.pshell.plot.LinePlot;
import ch.psi.pshell.plot.LinePlotBase;
import ch.psi.pshell.plot.LinePlotJFree;
import ch.psi.pshell.plot.LinePlotSeries;
import ch.psi.pshell.plot.Plot;
import ch.psi.pshell.ui.Panel;

/**
 *
 */
public class NetbeansPlugin extends Panel {

    public NetbeansPlugin() {
        initComponents();
        plot = new LinePlotJFree();
        plot.setTitle("");
        series1 = new LinePlotSeries("data", Color.RED);
        plot.addSeries(series1);
        series2 = new LinePlotSeries("data2", Color.BLUE, 2);
        plot.addSeries(series2);
        plot.getAxis(Plot.AxisId.X).setRange(0, 1000);
        plot.getAxis(Plot.AxisId.Y).setRange(-1.5, 1.5);
        plot.getAxis(Plot.AxisId.Y2).setRange(-1000.0, 2000.0);
        plot.getAxis(Plot.AxisId.Y2).setLabel("TEST");
        panelPlot.add(plot);
        getApp().addTask(task);
    }

    Task task = new Task() {
        @Override
        protected Object execute() throws Exception {
            series1.clear();
            series2.clear();

            extSeries1.clear();
            extSeries2.clear();
            for (int i = 0; i <= 1000; i++) {
                double v1 = Math.sin(i);
                double v2 = i + v1 * 100;
                series1.appendData(i, v1);
                series2.appendData(i, v2);

                extSeries1.appendData(i, v1);
                extSeries2.appendData(i, v2);

                Thread.sleep(5);
            }
            return true;
        }
    };

    LinePlotBase plot;
    LinePlotSeries series1;
    LinePlotSeries series2;

    LinePlotSeries extSeries1;
    LinePlotSeries extSeries2;

    @Override
    public void onStateChange(State state, State former) {
        setEnabled(state == State.Ready);
    }

    @Override
    public void onExecutedFile(String fileName, Object result) {
        if (IO.getPrefix(fileName).equals("test11")) {
            if (result instanceof Exception) {
                getLogger().log(Level.SEVERE, "Script execution failed: " + ((Exception) result).getMessage());
            } else {
                try {
                    runAsync("test10");
                } catch (Exception ex) {
                    SwingUtils.showException(null, ex);
                }
            }
        }
    }

    @Override
    public void setEnabled(boolean value) {
        super.setEnabled(value);
        buttonExecute.setEnabled(value);
        buttonJava.setEnabled(value);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonExecute = new javax.swing.JButton();
        buttonAbort = new javax.swing.JButton();
        panelPlot = new javax.swing.JPanel();
        buttonJava = new javax.swing.JButton();

        buttonExecute.setText("Execute Script");
        buttonExecute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonExecuteActionPerformed(evt);
            }
        });

        buttonAbort.setText("Abort");
        buttonAbort.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAbortActionPerformed(evt);
            }
        });

        panelPlot.setLayout(new java.awt.BorderLayout());

        buttonJava.setText("Execute Java Code");
        buttonJava.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonJavaActionPerformed(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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(panelPlot, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(buttonJava)
                            .addComponent(buttonExecute))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 100, Short.MAX_VALUE)
                        .addComponent(buttonAbort, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(44, 44, 44)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonAbort, buttonExecute, buttonJava});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonExecute)
                    .addComponent(buttonAbort))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonJava, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelPlot, javax.swing.GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void buttonExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExecuteActionPerformed
        try {
                //Run script
            //run("test1");

            //Alternatives to run script with arguments
            /*
             eval("start = 22.0");
             eval("end = 32.0");
             eval("step = 10");
             runAsync("test11");
             */
            HashMap args = new HashMap();
            args.put("start", 20.0);
            args.put("end", 52.0);
            args.put("step", 20);
            runAsync("test11", args);

            //eval("run('test11', locals = {'start':10.0, 'end':50.0, 'step':40})");
            //evalAsync("run('test11', locals = {'start':10.0, 'end':50.0, 'step':40})");
        } catch (Exception ex) {
            SwingUtils.showException(this, ex);
        }
    }//GEN-LAST:event_buttonExecuteActionPerformed

    private void buttonAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAbortActionPerformed
        abort();
    }//GEN-LAST:event_buttonAbortActionPerformed

    private void buttonJavaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonJavaActionPerformed
        try {
            PlotDescriptor plots1 = new PlotDescriptor("Plot 1");
            PlotDescriptor plots2 = new PlotDescriptor("Plot 2");
            ArrayList<LinePlot> externalPlots = getContext().plot(new PlotDescriptor[]{plots1, plots2}, null);
            externalPlots.get(0).getAxis(Plot.AxisId.X).setRange(0, 1000);
            externalPlots.get(1).getAxis(Plot.AxisId.X).setRange(0, 1000);
            externalPlots.get(0).getAxis(Plot.AxisId.Y).setRange(-1.5, 1.5);
            externalPlots.get(1).getAxis(Plot.AxisId.Y).setRange(-1000.0, 2000.0);
            extSeries1 = externalPlots.get(0).getSeries(0);
            extSeries2 = externalPlots.get(1).getSeries(0);
            getApp().startTask(task);
        } catch (Exception ex) {
            SwingUtils.showException(this, ex);
        }

    }//GEN-LAST:event_buttonJavaActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonAbort;
    private javax.swing.JButton buttonExecute;
    private javax.swing.JButton buttonJava;
    private javax.swing.JPanel panelPlot;
    // End of variables declaration//GEN-END:variables
}
