/**
 * Copyright (c) Artenum SARL 2004-2005
 * @author Julien Forest / Sebastien Jourdain
 *
 * All rights reserved. This software can
 * not be used or copy or diffused without
 * an explicit license of Artenum SARL, Paris-France
 */
package com.artenum.cassandra.plugin.probingline;

import com.artenum.cassandra.pipeline.PipeLineManager;
import com.artenum.cassandra.pipeline.CassandraObject;
import com.artenum.cassandra.plugin.PlugInControlUI;
import com.artenum.cassandra.util.VtkObjectComboBoxModel;

import vtk.vtkDataSet;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.event.ChangeEvent;

/**
 * <pre>
 * &lt;b&gt;Project ref           :&lt;/b&gt; CASSANDRA project
 * &lt;b&gt;Copyright and license :&lt;/b&gt; See relevant sections
 * &lt;b&gt;Status                :&lt;/b&gt; under development
 * &lt;b&gt;Creation              :&lt;/b&gt; 04/03/2005
 * &lt;b&gt;Modification          :&lt;/b&gt;
 * &lt;b&gt;Description  :&lt;/b&gt; Control panel for the probing line plugin.
 * 
 * </pre>
 * <table cellpadding="3" cellspacing="0" border="1" width="100%">
 * <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
 * <td><b>Version number</b></td>
 * <td><b>Author (name, e-mail)</b></td>
 * <td><b>Corrections/Modifications</b></td>
 * </tr>
 * <tr>
 * <td>0.1</td>
 * <td>Julien Forest, j.forest@artenum.com</td>
 * <td>Creation</td>
 * </tr>
 * <tr>
 * <td>0.2</td>
 * <td>Sebastien Jourdain, jourdain@artenum.com</td>
 * <td>Modification</td>
 * </tr>
 * </table>
 * 
 * @author Julien Forest, Benoit Thiebault, Jeremie Turbet, Sebastien Jourdain
 * @version 1.3
 */
public class ProbingLineControlUI extends PlugInControlUI {
	// plugin data
	private PipeLineManager pipeLineManager;
	private ProbingLinePlugin plugin;
	private VtkObjectComboBoxModel datasetModel;

	// plugin ui
	private JComboBox inputDataset;
	private JFormattedTextField aX;
	private JFormattedTextField aY;
	private JFormattedTextField aZ;
	private JFormattedTextField bX;
	private JFormattedTextField bY;
	private JFormattedTextField bZ;
	private JFormattedTextField resolution;
	private JCheckBox viewPlot2D;
	private JRadioButton indexRBut;
	private JRadioButton xRBut;
	private JRadioButton yRBut;
	private JRadioButton zRBut;
	private JRadioButton sRBut;
	private JCheckBox widgetCheckBox;

	public final String UPDATE = "command.update";
	public final String EXPORT = "command.export";
	public final String CANCEL = "command.cancel";

	/**
	 * Define and set the control panel for the probing line plugin.Main
	 * constructor.
	 * 
	 * @param pipeLineManager
	 * @param plugin
	 * @param owner
	 */
	public ProbingLineControlUI(PipeLineManager pipeLineManager, ProbingLinePlugin plugin, Frame owner) {
		super(owner, "Probe configuration panel");
		this.pipeLineManager = pipeLineManager;
		this.plugin = plugin;
		datasetModel = new VtkObjectComboBoxModel(pipeLineManager.getDataSetList(), plugin.getOutputDataSet());

		// Dialog box
		getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));

		// Input dataset
		JPanel line = new JPanel(new BorderLayout());
		line.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 1), "Input dataset"));
		inputDataset = new JComboBox(datasetModel);
		inputDataset.addActionListener(this);
		line.add(inputDataset, BorderLayout.CENTER);
		line.setMaximumSize(new Dimension(10000, inputDataset.getHeight()));
		getContentPane().add(line);

		// Point A and B
		JPanel lineSettingPan = new JPanel();
		lineSettingPan.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 1), "Line settings"));
		lineSettingPan.setLayout(new BorderLayout());

		line = new JPanel(new GridLayout(3, 4));
		NumberFormat format = new DecimalFormat("#.###");
		aX = new JFormattedTextField(format);
		aX.setValue(0.0);
		aY = new JFormattedTextField(format);
		aY.setValue(0.0);
		aZ = new JFormattedTextField(format);
		aZ.setValue(0.0);
		bX = new JFormattedTextField(format);
		bX.setValue(1.0);
		bY = new JFormattedTextField(format);
		bY.setValue(1.0);
		bZ = new JFormattedTextField(format);
		bZ.setValue(1.0);
		line.add(new JPanel());
		line.add(new JLabel("X", JLabel.CENTER));
		line.add(new JLabel("Y", JLabel.CENTER));
		line.add(new JLabel("Z", JLabel.CENTER));
		line.add(new JLabel("A", JLabel.CENTER));
		line.add(aX);
		line.add(aY);
		line.add(aZ);
		line.add(new JLabel("B", JLabel.CENTER));
		line.add(bX);
		line.add(bY);
		line.add(bZ);
		lineSettingPan.add(line, BorderLayout.CENTER);

		// Vertical glue
		//line = new JPanel(new BorderLayout());
		//line.add(Box.createRigidArea(new Dimension(10, 10)), BorderLayout.NORTH);
		//getContentPane().add(line);

		// sampling resolution line
		JPanel resolutionPan = new JPanel();
		resolutionPan.setLayout(new BoxLayout(resolutionPan, BoxLayout.LINE_AXIS));
		resolutionPan.add(Box.createHorizontalGlue());
		resolutionPan.add(new JLabel("Resolution"));
		resolution = new JFormattedTextField(NumberFormat.getIntegerInstance());
		resolution.setValue(new Integer(256));
		resolutionPan.add(resolution);
		// lineSettingPan.add(resolutionPan);

		this.getContentPane().add(lineSettingPan);

		// plot settings
		JPanel plotPanel = new JPanel();
		plotPanel.setLayout(new BoxLayout(plotPanel, BoxLayout.PAGE_AXIS));
		plotPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 1), "2D Plot"));

		JPanel plotPan1 = new JPanel();
		plotPan1.setLayout(new BoxLayout(plotPan1, BoxLayout.LINE_AXIS));

		viewPlot2D = new JCheckBox("View plot", true);
		plotPan1.add(viewPlot2D);
		plotPan1.add(Box.createHorizontalGlue());
		plotPanel.add(plotPan1);

		JPanel plotPane2 = new JPanel();
		plotPane2.setLayout(new BoxLayout(plotPane2, BoxLayout.LINE_AXIS));

		ButtonGroup group = new ButtonGroup();
		indexRBut = new JRadioButton("index");
		plotPane2.add(indexRBut);
		group.add(indexRBut);

		xRBut = new JRadioButton("X");
		plotPane2.add(xRBut);
		group.add(xRBut);

		yRBut = new JRadioButton("Y");
		plotPane2.add(yRBut);
		group.add(yRBut);

		zRBut = new JRadioButton("Z");
		plotPane2.add(zRBut);
		group.add(zRBut);

		sRBut = new JRadioButton("S", true);
		plotPane2.add(sRBut);
		group.add(sRBut);

		plotPane2.add(Box.createHorizontalGlue());
		plotPanel.add(plotPane2);

		getContentPane().add(plotPanel);

		// 
		JPanel widgetLine = new JPanel();
		widgetLine.setLayout(new BoxLayout(widgetLine, BoxLayout.LINE_AXIS));
		widgetLine.add(Box.createHorizontalGlue());
		widgetCheckBox = new JCheckBox("Active 3D widget");
		widgetCheckBox.addItemListener(this);
		widgetLine.add(widgetCheckBox);
		getContentPane().add(widgetLine);

		// cmd line
		JPanel ctrLine = new JPanel();

		JButton export = new JButton("Export");
		export.setActionCommand(EXPORT);
		export.addActionListener(this);

		JButton update = new JButton("Update");
		update.setActionCommand(UPDATE);
		update.addActionListener(this);

		JButton cancel = new JButton("Cancel");
		cancel.setActionCommand(CANCEL);
		cancel.addActionListener(this);

		ctrLine.setLayout(new BoxLayout(ctrLine, BoxLayout.LINE_AXIS));
		ctrLine.add(export);
		ctrLine.add(Box.createHorizontalGlue());
		ctrLine.add(update);
		ctrLine.add(cancel);
		
		getContentPane().add(Box.createVerticalGlue());
		getContentPane().add(ctrLine);

		pack();
		// Dimension d = getSize();
		// setSize(d.width, d.height);
		setLocationRelativeTo(null);
	}

	public void actionPerformed(ActionEvent e) {
		performAction(e.getActionCommand());
	}
	
	   /**
     * set the selected input data set. 
     * @param selectedInput
     */
    public void setSelectedInput(CassandraObject selectedInput){
        if (selectedInput != null){
            inputDataset.getModel().setSelectedItem(selectedInput);
        } else {
            System.out.println("Selection is null");
        }
    }

	public void performAction(String command) {
		double[] startPt = new double[3];
		startPt[0] = ((Number) aX.getValue()).doubleValue();
		startPt[1] = ((Number) aY.getValue()).doubleValue();
		startPt[2] = ((Number) aZ.getValue()).doubleValue();

		double[] endPt = new double[3];
		endPt[0] = ((Number) bX.getValue()).doubleValue();
		endPt[1] = ((Number) bY.getValue()).doubleValue();
		endPt[2] = ((Number) bZ.getValue()).doubleValue();
		int res = ((Number) resolution.getValue()).intValue();
		if (command.equals(UPDATE)) {
			if (inputDataset.getSelectedItem() != null) {
				int plotType = -1;
				if (indexRBut.isSelected()) {
					plotType = 0;
				} else if (xRBut.isSelected()) {
					plotType = 1;
				} else if (yRBut.isSelected()) {
					plotType = 2;
				} else if (zRBut.isSelected()) {
					plotType = 3;
				} else if (sRBut.isSelected()) {
					plotType = 4;
				} else {
					System.out.println("Type not supported");
				}

				plugin.updateProbe((vtkDataSet) ((CassandraObject) datasetModel.getSelectedItem()).getVtkObject(), startPt, endPt, res, viewPlot2D.isSelected(),
						plotType);
				pipeLineManager.validateViewAndGo();
			} else {
				JOptionPane.showMessageDialog(new JFrame(), "Please select a valid input dataset.", "Input Filter Selection Error", JOptionPane.ERROR_MESSAGE);
				return;
			}
		} else if (command.equals(CANCEL)) {
		    plugin.show3DWidget(false);
			this.dispose();
		} else if (command.equals(EXPORT)) {
			plugin.export();
		}
	}

	public void update3DWidgetStatus(){
        plugin.show3DWidget(widgetCheckBox.isSelected());
    }
	
	/** Listens to the check boxes. */
	public void itemStateChanged(ItemEvent e) {

		Object source = e.getItemSelectable();

		if (source == widgetCheckBox) {
			plugin.show3DWidget(widgetCheckBox.isSelected());
		} else {
			System.out.println("Item not found");
		}
	}

	/**
	 * Set the coordinates of the entry point (point 1) of the probing line in
	 * the GUI.
	 * 
	 * @param pt
	 */
	public void setPoint1(double[] pt) {
		aX.setValue(pt[0]);
		aY.setValue(pt[1]);
		aZ.setValue(pt[2]);
	}
	
	public void setPoint1(double x, double y, double z) {
        aX.setValue(x);
        aY.setValue(y);
        aZ.setValue(z);
    }

	/**
	 * Set the coordinates of the exit point (point 2) of the probing line in
	 * the GUI.
	 * 
	 * @param pt
	 */
	public void setPoint2(double[] pt) {
		bX.setValue(pt[0]);
		bY.setValue(pt[1]);
		bZ.setValue(pt[2]);
	}

	public void setPoint2(double x, double y , double z) {
        bX.setValue(x);
        bY.setValue(y);
        bZ.setValue(z);
    }
	
	
    public void stateChanged(ChangeEvent arg0) {
        // TODO Auto-generated method stub
        
    }
}
