/******************************************************************************
* Copyright 1996-2014 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
******************************************************************************/

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;

/** General options dialog for CDFExport
 */

public class ExportGeneralOptions extends JDialog { 

    private static ExportGeneralOptions dialog;

    static final long serialVersionUID = 1L;

    private CDFExport cdfexport;
    private ButtonGroup orientationgp;
    private JRadioButton orientation1;
    private JRadioButton orientation2;
    private JTextField tfRow = new JTextField(3);
    private JTextField tfCol = new JTextField(3);
    Font  boldFont = new Font("Dialog", Font.BOLD, 12);

    private JCheckBox t0c;
    private JCheckBox rnc;
    private JCheckBox ric;
    private JCheckBox vhc;

    private ButtonGroup epochgp;
    private JRadioButton epoch0;
    private JRadioButton epoch1;
    private JRadioButton epoch2;
    private JRadioButton epoch3;
    private JRadioButton epochx;

    private ButtonGroup columngp;
    private JRadioButton columnAll;
    private JRadioButton columnSome;
    private int oldCol;

    static boolean defaultModal = true;

    private static final String ENTER = "Continue";
    private static final String RESET = "Reset";
    private static final String CANCEL = "Cancel";

    private ExportGeneralOptions(JFrame parentFrame, boolean modal) {
        super(parentFrame, modal);
    }

    public static ExportGeneralOptions createGeneralOptions(JFrame parentFrame, 
							    CDFExport cdfexport, 
							    boolean modal) {
	if (dialog == null) {
	  dialog = new ExportGeneralOptions(parentFrame, modal);
	  dialog.getContentPane().setLayout(new BorderLayout());
	}
	dialog.cdfexport = cdfexport;
	dialog.oldCol = cdfexport.COLUMNS;
	dialog.packUIs();

        Dimension ps = dialog.getSize();
        Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
        dialog.setLocation(ss.width/2 - ps.width/2,
                           ss.height/2 - ps.height/2);

//	dialog.setLocation(0, 0);
	return dialog;
    }

/** Reenter this dialog
 */

    public void displayGeneralOptions() {
//	dialog.pack();
//	dialog.setLocation(0, 0);
        dialog.setVisible(true);

    }

/** Pack all UIs into the dialog
 */
    private void packUIs() {

        dialog.setTitle("Output to Screen/Text File Options");

        // Only way to close is to use the buttons
        dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dialog.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
            }
        });

        dialog.setSize(650,400);

        JPanel mp = (JPanel) dialog.getContentPane();
        mp.setBorder(new EmptyBorder(10,10,10,10));

        buildUIs();

        JPanel generalOptionsPanel = new JPanel(true);
	JPanel forTable = new JPanel(true);

	JLabeledPanel dc = new JLabeledPanel("Display Control", new GridLayout(2,1));
	JLabeledPanel pRow = new JLabeledPanel("Rows per Display", new GridLayout(1,3));
	JLabeledPanel pCol = new JLabeledPanel("Columns per Display", new GridLayout(1,2));
	JPanel pRow1 = new JPanel();
	JPanel pCol1 = new JPanel(new GridLayout(2,1));
	JPanel pCol2 = new JPanel(new GridLayout(2,3));
	tfRow.setHorizontalAlignment(JTextField.CENTER);
	tfRow.setText("" + cdfexport.ROWS);
	tfCol.setHorizontalAlignment(JTextField.CENTER);
	tfCol.setText("" + cdfexport.COLUMNS);
	pRow1.add(new JLabel("Rows: "));
	pRow1.add(tfRow);
	pRow.add(pRow1);
	pRow.add(Box.createRigidArea(new Dimension(5,1)));
	pRow.add(Box.createRigidArea(new Dimension(5,1)));
	
	columnSome.setFont(boldFont);
	columnAll.setFont(boldFont);
	pCol1.add(columnSome);
	pCol1.add(columnAll);

	pCol2.add(tfCol);
        pCol2.add(Box.createRigidArea(new Dimension(5,1)));
	pCol2.add(Box.createRigidArea(new Dimension(5,1))); 
	pCol2.add(Box.createRigidArea(new Dimension(5,1)));
        pCol2.add(Box.createRigidArea(new Dimension(5,1)));
        pCol2.add(Box.createRigidArea(new Dimension(5,1)));

	dc.add(pRow);
	pCol.add(pCol1);
	pCol.add(pCol2);
	dc.add(pCol);

	tfRow.addActionListener(new XYListener());
	tfRow.setToolTipText("Number of rows per display. Avoid setting it too big!!!");
	tfCol.addActionListener(new XYListener());
	tfCol.setToolTipText("Number of columns per display.");

        GridBagLayout gbl = new GridBagLayout();
        GridBagConstraints gbc = new GridBagConstraints();

	Component dummy = Box.createRigidArea(new Dimension(20,1));
        generalOptionsPanel.setLayout(gbl);

        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

	gbc.gridwidth = 1;
        gbl.setConstraints(t0c, gbc);
        generalOptionsPanel.add(t0c);

        gbc.gridwidth = GridBagConstraints.RELATIVE;
        gbl.setConstraints(rnc, gbc);
        generalOptionsPanel.add(rnc);

	gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbl.setConstraints(ric, gbc);
        generalOptionsPanel.add(ric);

        gbc.gridwidth = 1;
        gbl.setConstraints(vhc, gbc);
        generalOptionsPanel.add(vhc);

        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbl.setConstraints(dummy, gbc);
        generalOptionsPanel.add(dummy);

        JLabeledPanel jp = new JLabeledPanel("Orientation");
        jp.setLayout(new BoxLayout( jp, BoxLayout.Y_AXIS ));
        jp.setAlignmentY(LEFT_ALIGNMENT);

        jp.add(orientation1);
        jp.add(orientation2);

        gbc.gridwidth = 1;
        gbl.setConstraints(jp, gbc);
        generalOptionsPanel.add(jp);

        JLabeledPanel jp5 = new JLabeledPanel("Epoch");
        jp5.setLayout(new BoxLayout( jp5, BoxLayout.Y_AXIS ));
        jp5.setAlignmentY(LEFT_ALIGNMENT);
        jp5.add(epoch0);
        jp5.add(epoch1);
        jp5.add(epoch2);
        jp5.add(epoch3);
//        jp5.add(epochf);
        jp5.add(epochx);
	gbc.gridwidth = GridBagConstraints.RELATIVE;
        gbl.setConstraints(jp5, gbc);
        generalOptionsPanel.add(jp5);

        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbl.setConstraints(dc, gbc);
        generalOptionsPanel.add(dc);

        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbl.setConstraints(Box.createVerticalStrut(20), gbc);
        generalOptionsPanel.add(Box.createVerticalStrut(20));

        mp.add(generalOptionsPanel, BorderLayout.CENTER);

	createButtonPanel(mp);

    }

/** Build User Interface items
 */

    private void buildUIs() {

        t0c = new JCheckBox("Translate -0.0 to 0.0", false);
        rnc = new JCheckBox("Show Record Number", true);
        ric = new JCheckBox("Show Indices", true);
        vhc = new JCheckBox("Show Variable Headings", true);

        OptionsListener optionsListener = new OptionsListener();
        t0c.addItemListener(optionsListener);
        t0c.setToolTipText("Translate -0.0 to 0.0 that VAXes or DEC Alpha/Open VMS can access");
        rnc.addItemListener(optionsListener);
        rnc.setToolTipText("Show the data value's record number in the output");
        ric.addItemListener(optionsListener);
        ric.setToolTipText("Show indices for data value (applicable only for vertical output)");
        vhc.addItemListener(optionsListener);
        vhc.setToolTipText("Show the headings for each variable in the output");

        orientationgp = new ButtonGroup();
        orientation1 = new JRadioButton("Vertical");
        orientation2 = new JRadioButton("Horizontal");
        OrientationListener orientationListener = new OrientationListener();
        orientation1.setActionCommand("0");
        orientation2.setActionCommand("1");
        orientation1.addActionListener(orientationListener);
        orientation2.addActionListener(orientationListener);
        orientation1.setSelected(true);
        orientationgp.add(orientation1);
        orientationgp.add(orientation2);
        orientation1.setToolTipText("Use vertical output orientation");
        orientation2.setToolTipText("Use horizontal output orientation... no record indices");

	columngp = new ButtonGroup();
	columnSome = new JRadioButton("Show Columns:");
	columnAll = new JRadioButton("Show All");
	columnSome.addActionListener(new ColumnListener());
	columnAll.addActionListener(new ColumnListener());
	columngp.add(columnSome);
	columngp.add(columnAll);
	columnSome.setSelected(true);
        columnSome.setToolTipText("Number of columns per display.");
        columnAll.setToolTipText("Show all columns in each scrollable display.");

        epochgp = new ButtonGroup();
        epoch0 = new JRadioButton("Standard");
        epoch1 = new JRadioButton("Epoch1");
        epoch2 = new JRadioButton("Epoch2");
        epoch3 = new JRadioButton("Epoch3");
//        epochf = new JRadioButton("Epochf");
        epochx = new JRadioButton("Epochx");
        EpochListener epochListener = new EpochListener();
        epoch0.setActionCommand("0");
        epoch1.setActionCommand("1");
        epoch2.setActionCommand("2");
        epoch3.setActionCommand("3");
//        epochf.setActionCommand("4");
        epochx.setActionCommand("5");
        epoch0.addActionListener(epochListener);
        epoch1.addActionListener(epochListener);
        epoch2.addActionListener(epochListener);
        epoch3.addActionListener(epochListener);
//        epochf.addActionListener(epochListener);
        epochx.addActionListener(epochListener);
        epoch0.setSelected(true);
        epochgp.add(epoch0);
        epochgp.add(epoch1);
        epochgp.add(epoch2);
        epochgp.add(epoch3);
//        epochgp.add(epochf);
        epochgp.add(epochx);
        epoch0.setToolTipText("Format: dd-mmm-yyyy hh:mm:ss.ccc");
        epoch1.setToolTipText("Format: yyyymmdd.ttttttt");
        epoch2.setToolTipText("Format: yyyymoddhhmmss");
        epoch3.setToolTipText("Format: yyyy-mo-ddThh:mm:ss.cccZ");
//        epochf.setToolTipText("Use a user-defined Fortran style format(N/A)");
        epochx.setToolTipText("Use a user-defined string with tokens as format");

    }

/** Create selection buttons at the bottom of panel
 */

    private void createButtonPanel(JPanel jp) {

        JButton enterButton = new JButton(ENTER);
        JButton resetButton = new JButton(RESET);
        JButton cancelButton = new JButton(CANCEL);
        JPanel buttonPanel = new JPanel(true);

        buttonPanel.add(enterButton);
        buttonPanel.add(Box.createRigidArea(new Dimension(20,1)));
        buttonPanel.add(resetButton);
        buttonPanel.add(Box.createRigidArea(new Dimension(20,1)));
        buttonPanel.add(cancelButton);

	SelectionListener selectionListener = new SelectionListener();
        enterButton.addActionListener(selectionListener);
        resetButton.addActionListener(selectionListener);
        cancelButton.addActionListener(selectionListener);

        enterButton.setToolTipText("Continue to the next step ...");
        resetButton.setToolTipText("Reset the selections to their defaults...");
        cancelButton.setToolTipText("Stop but keep the selections and retrun to the previous step...");

        jp.add(buttonPanel, BorderLayout.SOUTH);

    }

/** Reset the selection to the defaults
 */

    public void reset() {

	t0c.setSelected(false);
	rnc.setSelected(true);
        ric.setSelected(true);
	vhc.setSelected(true);
	orientation1.setSelected(true);
	epoch0.setSelected(true);
	tfRow.setText(""+cdfexport.ROWS);
	tfCol.setText(""+cdfexport.COLUMNS);

	cdfexport.epoch = 0;
	cdfexport.trans0 = 0;
	cdfexport.recordNum = 1;
	cdfexport.indiceNum = 1;
	cdfexport.headings = 1;
	cdfexport.orientation = 0;
	cdfexport.ROWS = 26;
	cdfexport.COLUMNS = 9;

    }

/** Action for checkboxs selection
 */

    private class OptionsListener implements ItemListener {
      public void itemStateChanged(ItemEvent evt) {
	Object obj = evt.getSource();
	if (obj == t0c) { // "Translate -0.0 to 0.0" checkbox
	      if (t0c.isSelected())
                cdfexport.trans0 = -1;
              else
                cdfexport.trans0 = 0;
	} else if (obj == rnc) { // "Show Record Number" checkbox
              if (rnc.isSelected()) {
		cdfexport.recordNum = 1;
		cdfexport.changedCDF = true;
	      } else {
		cdfexport.recordNum = 0;
		cdfexport.changedCDF = true;
	      }
        } else if (obj == ric) { // "Show Indices" checkbox
              if (ric.isSelected()) {
		if (orientation2.isSelected()) { // not allowed for horizontal
		  Toolkit.getDefaultToolkit().beep();
		  ric.setSelected(false);
		  return;
		}
                cdfexport.indiceNum = 1;
		cdfexport.changedCDF = true;
              } else {
                cdfexport.indiceNum = 0;
		cdfexport.changedCDF = true;
	      }
        } else if (obj == vhc) { // "Display Variable Headings" checkbox
              if (vhc.isSelected())
                cdfexport.headings = 1;
              else
                cdfexport.headings = 0;
	}
      }
    }

/** Action for radio buttons for column display control
 */

    private class ColumnListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           JRadioButton obj = (JRadioButton) e.getSource();
	   if (obj == columnSome) {
	     cdfexport.COLUMNS = oldCol;
	     tfCol.setText(""+cdfexport.COLUMNS);		
           } else {
	     oldCol = cdfexport.COLUMNS;
	     cdfexport.COLUMNS = 0;
	     tfCol.setText(" "); 
	   }
        }
    }

/** Action for the radio button for column output control
 */

    private class OrientationListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           cdfexport.orientation = Integer.parseInt(e.getActionCommand());

           if (cdfexport.orientation == 1) { // Use horizontal orientation
             ric.setSelected(false); // "Show Indices" should be unchecked
             cdfexport.indiceNum = 0;
           } else {
             ric.setSelected(true); // "Show Indices" should be checked
             cdfexport.indiceNum = 1;
           }
        }
    }

/** Action for radio buttons for Epoch
 */

    private class EpochListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           cdfexport.epoch = Integer.parseInt(e.getActionCommand());
        }
    }

/** Action for text field for row/column
 */

    private class XYListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
	   Object obj = e.getSource();
	   if (obj == tfRow) { // row count
	     try {
	        int rows = Integer.parseInt(tfRow.getText());
		if (rows < 0) {
		  Toolkit.getDefaultToolkit().beep();
		  tfRow.setText("" + cdfexport.ROWS);
		} else {
		  cdfexport.ROWS = rows;
		}
	     } catch (Exception ee) {
		Toolkit.getDefaultToolkit().beep();
		tfRow.setText("" + cdfexport.ROWS);
	     }
	   } else { // column count
             try {
                int cols = Integer.parseInt(tfCol.getText());
                if (cols < 0) {
                  Toolkit.getDefaultToolkit().beep();
                  tfCol.setText("" + cdfexport.COLUMNS);
                } else {
                  cdfexport.COLUMNS = cols;
		  columnSome.setSelected(true);
                }
             } catch (Exception ee) {
                Toolkit.getDefaultToolkit().beep();
                tfCol.setText("" + cdfexport.COLUMNS);
             }
	  }
        }
    }

/**
 * Process button events.
 */
    private class SelectionListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
          Object source = event.getSource();

          if (source instanceof JButton) {
            String action = event.getActionCommand();
            if (action.equals(CANCEL)) {              // Cancel the operation
                dialog.setVisible(false);
		cdfexport.repaint();
            } else if (action.equals(ENTER)) {        // Continue the operation
               try {
                  int rows = Integer.parseInt(tfRow.getText());
		  int cols;
		  if (columnSome.isSelected()) 
		    cols = Integer.parseInt(tfCol.getText());
		  else
		    cols = 0; 
		  if (rows < 0 || cols < 0) {
		    Toolkit.getDefaultToolkit().beep();
		    if (rows < 0) tfRow.setText("" + cdfexport.ROWS);
		    if (cols < 0) tfCol.setText("" + cdfexport.COLUMNS);
		  } else {
		    if (rows != cdfexport.ROWS) cdfexport.ROWS = rows;
		    if (cols != cdfexport.COLUMNS) cdfexport.COLUMNS = cols;
		    dialog.setVisible(false);
		    cdfexport.repaint();
		  }
               } catch (Exception ee) {
                  Toolkit.getDefaultToolkit().beep();
                  tfRow.setText("" + cdfexport.ROWS);
		  tfCol.setText("" + cdfexport.COLUMNS);
               }

            } else if (action.equals(RESET)) {        // Reset the selection
                reset();
            }
          }
        }
   }

}

