package iDSS.tidalData;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.sql.Timestamp;
import java.beans.*;
import java.io.*;




import iDSS.utils.*;
import iDSS.disp.*;
import iDSS.tables.*;
import iDSS.database.*;
import iDSS.beans2.*;
import iDSS.tidalData.*;







public class TidalStationsLocal extends DisplayFrame implements ActionListener,PropertyChangeListener {


    private ScrollingTable aTable;
    private JScrollPane scrollPane;

    private JButton fetchDataButton;
    private TimestampPanel startTimestamp,endTimestamp;
    private JPanel timesPanel,bottomPanel;
    private boolean ALLOW_ROW_SELECTION = true;
    private String dataCategory,dataType,dataSet,stationName,dataTable,dataLocation;
    private Timestamp startDate,endDate;
    private String title;


    private JComboBox databaseDriverCombo;
    private JComboBox dsnCombo;
    private JButton getStationsButton;
    private JTextField userNameTextField;
    private JPasswordField passwordField;
    private JTextField tableNameTextField;

    private DataManager dm;
    private TidalStationsLocalJBean tidalStationsLocalJBean;

    private JButton getDsnButton, getDatabaseDriversButton;



    public TidalStationsLocal(String aTitle) {

        super(aTitle,false,false,false,true,null);
        tidalStationsLocalJBean = new TidalStationsLocalJBean();
        tidalStationsLocalJBean.addPropertyChangeListener(this);

        title = aTitle;


        Vector stations = tidalStationsLocalJBean.getTidalStations();     //This is necessary for remote stations only

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

        aTable = new ScrollingTable(columnNames,stations,500,100,true,false);
        aTable.removePropertyChangeListener(this);
        aTable.addPropertyChangeListener(this);
        scrollPane = aTable.getScrollPane();


        databaseDriverCombo = new JComboBox(tidalStationsLocalJBean.getDatabaseDrivers());
        dsnCombo = new JComboBox(tidalStationsLocalJBean.getDataSourceNames());

        userNameTextField = new JTextField(12);
        passwordField = new JPasswordField(12);
        JLabel userNameLabel = new JLabel("User name:");
        JLabel passwordLabel = new JLabel("Password:");

        JPanel labelPanel2 = new JPanel();
        JPanel textFieldPanel = new JPanel();

        labelPanel2.setLayout(new GridLayout(2,1));
        textFieldPanel.setLayout(new GridLayout(2,1));

        labelPanel2.add(userNameLabel);
        labelPanel2.add(passwordLabel);

        textFieldPanel.add(userNameTextField);
        textFieldPanel.add(passwordField);

        tableNameTextField = new JTextField(5);
        JLabel tableNameLabel = new JLabel("Table name:");


        getStationsButton = new JButton(IDSSAppConstants.getStationsButtonText);
        getStationsButton.setActionCommand(IDSSAppConstants.getStationsButtonCommand);
        getStationsButton.addActionListener(this);


        getDsnButton = new JButton(IDSSAppConstants.getDsnButtonText);
        getDsnButton.setActionCommand(IDSSAppConstants.getDsnButtonCommand);
        getDsnButton.addActionListener(this);

        getDatabaseDriversButton = new JButton(IDSSAppConstants.getDatabaseDriversButtonText);
        getDatabaseDriversButton.setActionCommand(IDSSAppConstants.getDatabaseDriversButtonCommand);
        getDatabaseDriversButton.addActionListener(this);


        JLabel databaseDriverLabel = new JLabel("Database driver:");
        JLabel dsnLabel = new JLabel("Data source:");

        JPanel localStationsPanel = new JPanel();
        JPanel labelPanel = new JPanel();
        JPanel comboPanel = new JPanel();
        JPanel localStationsButtonPanel = new JPanel();
        JPanel localStationsAllPanel = new JPanel();

        labelPanel.setLayout(new GridLayout(2,1));
        labelPanel.add(databaseDriverLabel);
        labelPanel.add(dsnLabel);

        comboPanel.setLayout(new GridLayout(2,1));
        comboPanel.add(databaseDriverCombo);
        comboPanel.add(dsnCombo);

        localStationsPanel.setLayout(new BoxLayout(localStationsPanel,BoxLayout.X_AXIS));
        localStationsPanel.add(Box.createHorizontalStrut(2));
        localStationsPanel.add(labelPanel2);
        localStationsPanel.add(Box.createHorizontalStrut(2));
        localStationsPanel.add(textFieldPanel);
        localStationsPanel.add(Box.createHorizontalStrut(5));
        localStationsPanel.add(labelPanel);
        localStationsPanel.add(Box.createHorizontalStrut(2));
        localStationsPanel.add(comboPanel);
        localStationsPanel.add(Box.createHorizontalStrut(2));

        localStationsButtonPanel.setLayout(new BoxLayout(localStationsButtonPanel,BoxLayout.X_AXIS));
        localStationsButtonPanel.add(getStationsButton);
        localStationsButtonPanel.add(Box.createHorizontalStrut(2));
        localStationsButtonPanel.add(getDsnButton);
        localStationsButtonPanel.add(Box.createHorizontalStrut(2));
        localStationsButtonPanel.add(getDatabaseDriversButton);
        localStationsButtonPanel.add(Box.createHorizontalStrut(2));

        localStationsButtonPanel.add(tableNameLabel);
        localStationsPanel.add(Box.createHorizontalStrut(2));
        localStationsButtonPanel.add(tableNameTextField);

        localStationsAllPanel.setLayout(new BoxLayout(localStationsAllPanel,BoxLayout.Y_AXIS));
        localStationsAllPanel.add(localStationsPanel);
        localStationsAllPanel.add(localStationsButtonPanel);

        localStationsAllPanel.setBorder(BorderFactory.createEtchedBorder());

        fetchDataButton = new JButton(IDSSAppConstants.fetchDataButtonText);
        fetchDataButton.addActionListener(this);
        fetchDataButton.setActionCommand(IDSSAppConstants.fetchDataButtonCommand);
        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);
        bottomPanel.setBorder(BorderFactory.createEtchedBorder());


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

        pack();
        setVisible(true);

    }//public TidalStationsLocal(String aTitle)








    public void actionPerformed(ActionEvent ae) {


        if(ae.getActionCommand().equals(IDSSAppConstants.getStationsButtonCommand)) {

            String driver = (String)databaseDriverCombo.getSelectedItem();
            String dsn = (String)dsnCombo.getSelectedItem();
            String table = tableNameTextField.getText();
            String pw = new String(passwordField.getPassword());
            String user = userNameTextField.getText();


            if(driver.length() == 0 || dsn.length() == 0 || table.length() == 0 ||
                                pw.length() == 0 || user.length() == 0) {
                JOptionPane.showMessageDialog(null,"Fill up all input boxes",
                                            "Incomplete information",JOptionPane.ERROR_MESSAGE);

            } //if(...)

            else {

                Vector stations = tidalStationsLocalJBean.getLocalStations(driver,dsn,table,pw,user);
                if(stations != null)
                    aTable.addRows(stations);

            } //else

        } //if(ae.getActionCommand().equals(IDSSAppConstants.getStationsButtonCommand))


        else if(ae.getActionCommand().equals(IDSSAppConstants.fetchDataButtonCommand)) {

            startDate = startTimestamp.getTimestamp();
            endDate = endTimestamp.getTimestamp();

            String user = userNameTextField.getText();
            String pw = new String(passwordField.getPassword());
            String driver = (String)databaseDriverCombo.getSelectedItem();
            String dsn = (String)dsnCombo.getSelectedItem();

            tidalStationsLocalJBean.setUserName(user);
            tidalStationsLocalJBean.setPassword(pw);
            tidalStationsLocalJBean.setDatabaseDriver(driver);
            tidalStationsLocalJBean.setDsn(dsn);

            tidalStationsLocalJBean.fetchData(stationName,startDate,endDate,dataTable,dataLocation);

        } //if(ae.getActionCommand().equals(IDSSAppConstants.fetchDataButtonCommand))


        else if(ae.getActionCommand().equals(IDSSAppConstants.getDsnButtonCommand)) {


            File  dsnFile = FileNameDialog.getInputFileName("Select a DSN file",null,null);
            Vector dsnNamesVector = new Vector();

            if(dsnFile != null) {

                dsnNamesVector = ConfigData.readProperties(dsnFile);

                if(dsnNamesVector != null) {

                    for(int i=0;i<dsnNamesVector.size();i++) {

                        String s = (String)dsnNamesVector.elementAt(i);
                        dsnCombo.addItem(s);

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

                } //if(dsnNamesVector != null)

            } //if(dsnFile != null)


        } //else if(ae.getActionCommand().equals(IDSSAppConstants.getDsnButtonCommand))



        else if(ae.getActionCommand().equals(IDSSAppConstants.getDatabaseDriversButtonCommand)) {

            File  driversFile = FileNameDialog.getInputFileName("Select a database drivers file",null,null);
            Vector databaseDriversVector = new Vector();

            if(driversFile != null) {

                databaseDriversVector = ConfigData.readProperties(driversFile);

                if(databaseDriversVector != null) {

                    for(int i=0;i<databaseDriversVector.size();i++) {

                        String s = (String)databaseDriversVector.elementAt(i);
                        databaseDriverCombo.addItem(s);

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

                    String driverPath = ".";
                    File parentFile = driversFile.getParentFile();

                    if(parentFile != null)
                        driverPath = parentFile.toString();

                    System.out.println("TidalStationsLocal.actionPerformed(), driverPath: " + driverPath);
                    ConfigData.addToClassPath(driverPath);

                } //if(databaseDriversVector != null)

            } //if(dsnFile != null)


        } //else if(ae.getActionCommand().equals(IDSSAppConstants.getDatabaseDriversButtonCommand))





    }//public void actionPerformed(ActionEvent ae)






    private void addToModelView(DisplayFrame panel) {

        firePropertyChange(IDSSAppConstants.addToModelView,null,panel);

    } //private void addToModelView(DisplayFrame panel)






    public void propertyChange(PropertyChangeEvent evt) {

        if(evt.getPropertyName().equals(IDSSAppConstants.setTidalModel)) {

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

        } //if(evt.getPropertyName().equals(IDSSAppConstants.setTidalModel))



        if(evt.getPropertyName().equals(IDSSAppConstants.addToModelView)) {

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

        } //if(evt.getPropertyName().equals(IDSSAppConstants.addToModelView))



        if(evt.getPropertyName().equals(IDSSAppConstants.showMessage)) {

            Vector messageVector = (Vector)evt.getNewValue();
            MessageHandler.showMessage(messageVector);

        } //if(evt.getPropertyName().equals(IDSSAppConstants.plainMessage))



        if(evt.getPropertyName().equals(IDSSAppConstants.noRowsSelected)) {

            //System.out.println("TidalStationsLocal.propertyChange(), " + evt.getPropertyName());
            fetchDataButton.setEnabled(false);

        } //if(evt.getPropertyName().equals(IDSSAppConstants.noRowsSelected))


        if(evt.getPropertyName().equals(IDSSAppConstants.noColsSelected)) {

            System.out.println("TidalStationsLocal.propertyChange(), " + evt.getPropertyName());

        } //if(evt.getPropertyName().equals(IDSSAppConstants.noColsSelected))



        if(evt.getPropertyName().equals(IDSSAppConstants.oneRowSelected)) {

            //System.out.println("TidalStationsLocal.propertyChange(), " + evt.getPropertyName());

            Vector selectedRow = (Vector)evt.getNewValue();
            selectOneRow(selectedRow);

        } //if(evt.getPropertyName().equals(IDSSAppConstants.oneRowSelected))



        if(evt.getPropertyName().equals(IDSSAppConstants.oneColSelected)) {

            int selectedCol = ((Integer)evt.getNewValue()).intValue();

            String colName = aTable.getColumnName(selectedCol);

        } //if(evt.getPropertyName().equals(IDSSAppConstants.oneColSelected))


        if(evt.getPropertyName().equals(IDSSAppConstants.tidalData)) {

            ClientDataSet cds = (ClientDataSet)evt.getNewValue();

            if(cds != null) {
                receiveData(cds);
            }//if(cds == null)

        } //if(evt.getPropertyName().equals(IDSSAppConstants.tidalData)


        if(evt.getPropertyName().equals(IDSSAppConstants.disposeData)) {

            Vector dataVector = (Vector)evt.getNewValue();

            if(dataVector != null) {

                tidalStationsLocalJBean.disposeData(dataVector);

            } //if(dataVector != null)

        } //if(evt.getPropertyName().equals(IDSSAppConstants.disposeData))


    } //public void propertyChange(PropertyChangeEvent evt)







    private void selectOneRow(Vector selectedRow) {

        fetchDataButton.setEnabled(true);

        stationName = (String) selectedRow.elementAt(0);
        Timestamp startDate = (Timestamp) selectedRow.elementAt(1);
        Timestamp endDate = (Timestamp) selectedRow.elementAt(2);
        dataTable = (String) selectedRow.elementAt(3);
        dataLocation = (String) selectedRow.elementAt(4);

        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);


        for(int i=0;i<selectedRow.size();i++) {

            String s = selectedRow.elementAt(i).toString();
            System.out.println(s);

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


    } //private void selectOneRow()





    private void receiveData(ClientDataSet cds) {

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

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

    } //private void receiveData(ClientDataSet cds)






    public String toString() {

        return "TidalStationsLocal: " + title;

    } //public String toString()



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