package iDSS.tidalData;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import javax.swing.table.*;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import java.sql.Timestamp;
import java.beans.*;


import iDSS.utils.*;
import iDSS.disp.*;
import iDSS.tables.*;

import ejb.dataAccess.*;


public class TidalStations extends DisplayFrame implements ActionListener,PropertyChangeListener {


  private JTable aTable;
  private JScrollPane aScrollPane;
  private JButton fetchDataButton;
  private TimestampPanel startTimestamp,endTimestamp;
  private JPanel timesPanel,bottomPanel;
  private boolean ALLOW_ROW_SELECTION = true;
  private String dataCategory,dataType,dataSet,stationName,dataTable;
  private Timestamp startDate,endDate;
  private Vector history;
  private String title;

  DataManager dm;




  public TidalStations(String aTitle, Vector row, Vector column) {

    super (aTitle,false,false,false,true,null);
    aTable = new JTable (row,column);
    aTable.setPreferredScrollableViewportSize(new Dimension(500, 50));
    aScrollPane = new JScrollPane(aTable);
    fetchDataButton = new JButton("Fetch data");

    //getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
    getContentPane().add(aScrollPane,BorderLayout.CENTER);
    getContentPane().add(fetchDataButton,BorderLayout.SOUTH);
    pack();
    setVisible(true);

  }//public TidalStations(int row, int column)





    private void getTidalStations() {


        iDSS.beans.TidalStationsJBean tsBean = new iDSS.beans.TidalStationsJBean();
        tsBean.setEjbName("TidalStationsEJB");

        Vector stations = tsBean.findAll();
        Vector columnNames = new Vector();
        columnNames.add("Station Name");
        columnNames.add("Start Date");
        columnNames.add("End Date");
        columnNames.add("Data Table");

        GeneralTableModel tm = new GeneralTableModel(stations,columnNames);
        aTable = new JTable(tm);

    } //private void getTidalStation()






  //public TidalStations(IDSSMain aParent, String aTitle, AbstractTableModel aTableModel) {

  public TidalStations(String aTitle) {

    super(aTitle,false,false,false,true,null);
    title = aTitle;
    history = new Vector();

    getTidalStations();

    //aTable = new JTable (aTableModel);
    //aTable = new JTable ();

    aTable.setPreferredScrollableViewportSize(new Dimension(500, 100));

    aTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);



    if (ALLOW_ROW_SELECTION) { // true by default
        ListSelectionModel rowSM = aTable.getSelectionModel();
        rowSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                //Ignore extra messages.
                if (e.getValueIsAdjusting()) return;
                
                ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.out.println("No rows are selected.");
                    fetchDataButton.setEnabled(false);
                } else {
                    int selectedRow = lsm.getMinSelectionIndex();
                    System.out.println("Row " + selectedRow
                                       + " is now selected.");
                    fetchDataButton.setEnabled(true);

                    stationName = (String) aTable.getValueAt(selectedRow,0);
                    Timestamp startDate = (Timestamp) aTable.getValueAt(selectedRow,1);
                    Timestamp endDate = (Timestamp) aTable.getValueAt(selectedRow,2);
                    dataTable = (String) aTable.getValueAt(selectedRow,3);


                    Calendar aCalendar = Calendar.getInstance();
                    aCalendar.setTime(startDate);
                    int startYear = aCalendar.get(Calendar.YEAR);
                    aCalendar.setTime(endDate);
                    int endYear = aCalendar.get(Calendar.YEAR);

                    startTimestamp.resetYearCombo(startYear,endYear);
                    endTimestamp.resetYearCombo(startYear,endYear);

                    startTimestamp.setTime(startDate);
                    endTimestamp.setTime(endDate);


                    //System.out.println("Years : " + startYear + ", " + endYear);


                }
            }
        });
    } else {
        aTable.setRowSelectionAllowed(false);
    }






    aScrollPane = new JScrollPane(aTable);
    fetchDataButton = new JButton("Fetch data");
    fetchDataButton.addActionListener(this);
    fetchDataButton.setActionCommand("fetchData");
    fetchDataButton.setEnabled(false);

    startTimestamp = new TimestampPanel("Start:",1900,2050);
    endTimestamp = new TimestampPanel("End:",1900,2050);

    timesPanel = new JPanel();
    timesPanel.setLayout(new GridLayout(2,1));
    timesPanel.add(startTimestamp);
    timesPanel.add(endTimestamp);

    bottomPanel = new JPanel();
    bottomPanel.setLayout(new BoxLayout(bottomPanel,BoxLayout.X_AXIS));
    bottomPanel.add(fetchDataButton);
    bottomPanel.add(timesPanel);

//    getContentPane().add(aScrollPane,BorderLayout.CENTER);
//    getContentPane().add(fetchDataButton,BorderLayout.SOUTH);


    getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
    getContentPane().add(aScrollPane);
    getContentPane().add(bottomPanel);

    pack();
    setVisible(true);

  }//public TidalStations(String aTitle)








  public void actionPerformed(ActionEvent ae) {


    if(ae.getActionCommand().equals("fetchData")) {
      System.out.println("fetchDataButton clicked");
      startDate = startTimestamp.getTimestamp();
      endDate = endTimestamp.getTimestamp();

      if (!startDate.after(endDate)) {

          boolean proceed = true;

          for (int i=0;i<history.size();i++) {
            Vector currentRow = (Vector) history.elementAt(i);
            String station = (String) currentRow.elementAt(0);
            Timestamp start = (Timestamp) currentRow.elementAt(1);
            Timestamp end = (Timestamp) currentRow.elementAt(2);

            if(stationName.equals(station)) {
                if((startDate.after(start)) || (startDate.equals(start)))
                    if((endDate.before(end)) || (endDate.equals(end)))
                        proceed = false;

            }

          } //for (int i=0;i<history.size();i++)


          int option = JOptionPane.YES_OPTION;

          if (!proceed)
            option = JOptionPane.showConfirmDialog(null,"You already have a superset of this data.\nProceed anyway?","Confirm",
                                                    JOptionPane.YES_NO_OPTION,
                                                    JOptionPane.QUESTION_MESSAGE);

          if (option == JOptionPane.YES_OPTION)
            proceed = true;
          else
            proceed = false;

          if (proceed) {

              System.out.println("Proceeding with fetchData");


                ClientDataSet cds = fetchData(stationName,startDate,endDate);

                if(dm == null) {
                    dm = new DataManager(cds);
                    dm.addPropertyChangeListener(this);
                    addToModelView(dm);
                } //if(dm == null)

                else {
                    dm.addToDataSet(cds);
                } //else

              //parentComponent.fetchData(stationName,startDate,endDate);

              Vector currentRow = new Vector();
              currentRow.add(stationName);
              currentRow.add(startDate);
              currentRow.add(endDate);
              history.add(currentRow);

          } //if (proceed)
          else
            System.out.println("You already have a superset of this data");

      } //if (!startDate.after(endDate))

    } //if(ae.getActionCommand().equals("fetchData"))


  }//public void actionPerformed(ActionEvent ae)









    private ClientDataSet fetchData(String dataTable,Timestamp start,Timestamp end) {

        iDSS.beans.TidalDataJBean tdBean = new iDSS.beans.TidalDataJBean();
        tdBean.setEjbName("TidalDataEJB");
        String dbName = "java:comp/env/jdbc/idss";
        ClientDataSet cds = tdBean.select(dataTable,start,end,dbName);
        return cds;

    } //private ClientDataSet fetchData(String dataTable,Timestamp start,Timestamp end)





    private void addToModelView(DisplayFrame panel) {

        firePropertyChange(IDSSAppConstants.addToModelView,null,panel);

    } //private void addToModelView(DisplayFrame panel)




    public void propertyChange(PropertyChangeEvent evt) {


        if((!evt.getPropertyName().equals("layeredContainerLayer")) &&
            (!evt.getPropertyName().equals("ancestor")) &&
                (!evt.getPropertyName().equals("selected"))) {

            firePropertyChange(evt.getPropertyName(),evt.getOldValue(),evt.getNewValue());

        } //


    } //public void propertyChange(PropertyChangeEvent evt)




    public String toString() {

        return "TidalStations: " + title;

    } //public String toString()



} //public class TidalStations extends DisplayFrame implements ActionListener,PropertyChangeListener
