package iDSS.sm;

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.beans.*;
import java.io.*;


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



public class SurvivalModelsList extends DisplayFrame implements ActionListener, PropertyChangeListener {


    private JTable aTable;
    private JScrollPane aScrollPane;
    private JButton detailsButton,pickFromFileButton,selectAllButton,defineButton;
    private JButton pickAllButton;
    private JButton saveAllButton;
    private JComboBox defineCombo;
    private JButton userSMButton;

    private JPanel buttonPanel,buttonPanel2,buttonPanel3;
    private boolean ALLOW_ROW_SELECTION = true;

    private Vector columnNames;
    private Vector rowsOfData;

    private String lcClass,currentSurvivalModelName;


    private JTextField floodLcTextField;

    private SurvivalModel currentSurvivalModel;
    //private Hashtable survivalModelsHashtable;
    private JComboBox classTypesCombo;

    private File currentPath;

    //private final char backSlash = 92;
    private final char backSlash = File.separatorChar;
    private final char foreSlash = 47;
    private File currentFile;

    private SurvivalModelsListJBean smListJBean;







    public SurvivalModelsList(String title) {

        super (IDSSAppConstants.smListTitle,false,false,false,true,null);

        smListJBean = new SurvivalModelsListJBean();
        smListJBean.addPropertyChangeListener(this);

        columnNames = smListJBean.getColumnNames();
        Vector rowsOfData = new Vector();

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

        aTable.setPreferredScrollableViewportSize(new Dimension(50,75));
        aTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        aScrollPane = new JScrollPane(aTable);

        detailsButton = new JButton(IDSSAppConstants.detailsButtonText);
        pickFromFileButton = new JButton(IDSSAppConstants.pickButtonText);
        selectAllButton = new JButton(IDSSAppConstants.selectAllButtonText);
        defineButton = new JButton(IDSSAppConstants.defineButtonText);
        pickAllButton = new JButton(IDSSAppConstants.pickAllButtonText);
        saveAllButton = new JButton(IDSSAppConstants.saveAllButtonText);

        detailsButton.addActionListener(this);
        pickFromFileButton.addActionListener(this);
        selectAllButton.addActionListener(this);
        defineButton.addActionListener(this);
        pickAllButton.addActionListener(this);
        saveAllButton.addActionListener(this);

        detailsButton.setActionCommand(IDSSAppConstants.detailsButtonCommand);
        pickFromFileButton.setActionCommand(IDSSAppConstants.pickButtonCommand);
        selectAllButton.setActionCommand(IDSSAppConstants.selectAllButtonCommand);
        defineButton.setActionCommand(IDSSAppConstants.defineButtonCommand);
        pickAllButton.setActionCommand(IDSSAppConstants.pickAllButtonCommand);
        saveAllButton.setActionCommand(IDSSAppConstants.saveAllButtonCommand);

        detailsButton.setEnabled(false);
        pickFromFileButton.setEnabled(true);
        selectAllButton.setEnabled(false);
        defineButton.setEnabled(true);
        pickAllButton.setEnabled(true);
        saveAllButton.setEnabled(true);

        classTypesCombo = new JComboBox();
        defineCombo = new JComboBox(smListJBean.getSmModelNames());

        userSMButton = new JButton(IDSSAppConstants.getUserSMButtonText);
        userSMButton.setActionCommand(IDSSAppConstants.getUserSMButtonCommand);
        userSMButton.addActionListener(this);

        buttonPanel = new JPanel();
        buttonPanel.add(detailsButton);
        buttonPanel.add(pickFromFileButton);
        buttonPanel.add(classTypesCombo);
        buttonPanel.add(defineButton);

        buttonPanel2 = new JPanel();
        buttonPanel2.add(userSMButton);
        buttonPanel2.add(defineCombo);

        buttonPanel3 = new JPanel();
        buttonPanel3.add(selectAllButton);
        buttonPanel3.add(pickAllButton);
        buttonPanel3.add(saveAllButton);

        getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
        getContentPane().add(aScrollPane);
        getContentPane().add(buttonPanel);
        getContentPane().add(buttonPanel2);
        getContentPane().add(buttonPanel3);
        pack();
        setVisible(true);


        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.");
                        detailsButton.setEnabled(false);
                        //selectAllButton.setEnabled(false);
                    } else {
                        int selectedRow = lsm.getMinSelectionIndex();
                        System.out.println("Row " + selectedRow
                                           + " is now selected.");

                        detailsButton.setEnabled(true);
                        //selectAllButton.setEnabled(true);

                        lcClass = (String) aTable.getValueAt(selectedRow,0);
                        classTypesCombo.setSelectedItem(lcClass);

                        currentSurvivalModelName = (String) aTable.getValueAt(selectedRow,1);

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


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






    public void setClassTypes(Vector v) {


        if(v != null) {

            classTypesCombo.removeAllItems();

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

                String s = (String)v.elementAt(i);
/**
                int decimalPlace = s.indexOf(".");
                String s2 = s.substring(0,decimalPlace);
                classTypesCombo.addItem(s2);
**/
                classTypesCombo.addItem(s);

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

            smListJBean.setClassTypes(v);

        } //if(v != null)

    } //public void setClassTypes(Vector v)







    public String getCurrentClassType() {

        String currentClassType = (String) classTypesCombo.getSelectedItem();
        return currentClassType;

    } //public String getCurrentClassType()
    





      public void actionPerformed(ActionEvent ae) {


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


            SurvivalModel sm = smListJBean.showDetails(getCurrentClassType(),false);

            if(sm != null) {

                sm.addPropertyChangeListener(this);
                firePropertyChange(IDSSAppConstants.addToModelView,null,sm.showDetails(false));

            } //if(sm != null)

            else
                JOptionPane.showMessageDialog(null,"Specified file is not a Survival Model",
                                        "Error",JOptionPane.ERROR_MESSAGE);

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



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


            String currentModel = (String) defineCombo.getSelectedItem();
            //SurvivalModel sm = smListJBean.define(currentModel);
            SurvivalModel sm = smListJBean.define(currentModel);

            if(sm != null) {

                sm.addPropertyChangeListener(this);
                firePropertyChange(IDSSAppConstants.addToModelView,null,sm.showDetails(true));

            }//if(sm != null)



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



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

            System.out.println("pick from file clicked");
            String currentClassType = (String) classTypesCombo.getSelectedItem();

            if (currentClassType != null) {

                String approveButtonText = "SurvivalModel: Class " + currentClassType;

                File inFile = FileNameDialog.getInputFileName(approveButtonText,currentPath,null);

                String inFileName;

                if (inFile != null) {

                    System.out.println("inFile.toString() : " + inFile.toString());
                    inFileName = inFile.toString();

                    addToTable(currentClassType,inFileName);
                    smListJBean.addToHashtable(currentClassType,inFileName);

                    currentPath = inFile.getParentFile();

                } //if (inFile != null)

            } //if (currentClassType != null)

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



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

            System.out.println("select clicked");
            //setSurvivalModels();
            saveSurvivalModels();

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



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

            Hashtable smHashtable = smListJBean.getSurvivalModels();
            firePropertyChange(IDSSAppConstants.setAllSurvivalModels,null,smHashtable);

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




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

            pickAll();

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




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

            File userSMFile = FileNameDialog.getInputFileName("Select User SM File",null,null);
            Vector userSMVector = new Vector();

            if(userSMFile != null) {

                userSMVector = ConfigData.readProperties(userSMFile);

                if(userSMVector != null) {

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

                        String s = (String)userSMVector.elementAt(i);
                        defineCombo.addItem(s);

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

                    String smPath = ".";
                    File parentFile = userSMFile.getParentFile();

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

                    System.out.println("SurvivalModelsList.actionPerformed(), smpath: " + smPath);
                    ConfigData.addToClassPath(smPath);
                    smListJBean.addCustomClasses(smPath,userSMVector);

                } //if(dsnNamesVector != null)

            } //if(dsnFile != null)


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





      }//public void actionPerformed(ActionEvent ae)










    private void pickAll() {


        File file = FileNameDialog.getInputFileName(IDSSAppConstants.pickAllButtonText,null,null);

        if (file != null) {

            Hashtable survivalModelsHashtable = smListJBean.pickAll(file);

            Vector rows = new Vector();
            Enumeration keys = survivalModelsHashtable.keys();

            while(keys.hasMoreElements()) {

                String key = (String)keys.nextElement();
                String sm = (String)survivalModelsHashtable.get(key);

                Vector oneRow = new Vector();
                oneRow.add(key);
                //sm = sm.replace(backSlash,foreSlash);
                oneRow.add(sm);

                rows.add(oneRow);

                System.out.println(key + "\t" + sm);

            } //if(keys.hasMoreElements())

            GeneralTableModel tm = (GeneralTableModel) aTable.getModel();
            Vector columns = tm.getColumns();
            GeneralTableModel tm2 = new GeneralTableModel(rows,columns);
            aTable.setModel(tm2);


            if(survivalModelsHashtable.size() >= classTypesCombo.getItemCount()) {
                selectAllButton.setEnabled(true);
            } //if(survivalModelsHashtable.size() >= classTypesCombo.getItemCount())

            else {
                selectAllButton.setEnabled(false);
            } //else


        } //if (inFile != null)


    } //private void pickAll()













    public void propertyChange(PropertyChangeEvent evt) {


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

            SurvivalModel sm = (SurvivalModel)evt.getNewValue();

            JOptionPane.showMessageDialog(null,"Reached propertyChange method with a " + sm.getName(),
                                    "Information",JOptionPane.INFORMATION_MESSAGE);

            if(sm != null && sm instanceof SurvivalModel) {

                JOptionPane.showMessageDialog(null,"Successfully received Survivalodel",
                                        "Information",JOptionPane.INFORMATION_MESSAGE);

                setNewSurvivalModel(sm,getCurrentClassType());

            } //if(sm != null && sm instanceof SurvivalModel)

            else {

                JOptionPane.showMessageDialog(null,"Failed to receive Survivalodel",
                                        "Error",JOptionPane.ERROR_MESSAGE);
                
            } //else

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



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

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

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



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

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

        } //if(evg.getPropertyName().equals(IDSSAppConstants.removeFromModelView))



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

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

        } //if(evg.getPropertyName().equals(IDSSAppConstants.showMessage))



    } //public void propertyChange(PropertyChangeEvent evt)








    public void addToTable(String currentClassType, String inFileName) {


        if(smListJBean.containsClass(currentClassType)) {

            System.out.println("Removing... " + currentClassType + " from survivalModelsHashtable");

            Vector currentRow = new Vector();

            currentRow.add(currentClassType);

            //String s = (String)survivalModelsHashtable.get(currentClassType);

            String s = smListJBean.getSurvivalModel(currentClassType);

            //s = s.replace(backSlash,foreSlash);
            currentRow.add(s);

            GeneralTableModel tm = (GeneralTableModel) aTable.getModel();

            tm.removeRow(currentRow);
            aTable.setModel(tm);

            smListJBean.removeFromHashtable(currentClassType);

        } //if(smListJBean.containsClass(currentClassType))


        smListJBean.addToHashtable(currentClassType,inFileName);

        //inFileName = inFileName.replace(backSlash,foreSlash);

        GeneralTableModel tm = (GeneralTableModel) aTable.getModel();

        Vector rowVector = new Vector();
        rowVector.add(currentClassType);
        rowVector.add(inFileName);

        tm.addRow(rowVector);
        aTable.setModel(tm);


        saveAllButton.setEnabled(true);

        if(smListJBean.getHashtableSize() >= classTypesCombo.getItemCount()) {
            selectAllButton.setEnabled(true);
        } //if(smListJBean.getHashtableSize() >= classTypesCombo.getItemCount())

        else {
            selectAllButton.setEnabled(false);
        } //else


    } //public void addToTable(String currentClassType, String inFileName)







    private void saveSurvivalModels() {


        //File file = writeToFile(survivalModelsHashtable);

        File file = FileNameDialog.getOutputFileName("Save",null,null);
        boolean success = false;

        if(file != null) {

            success = smListJBean.saveSurvivalModels(file);

        } //if(file != null)


        if(success) {

            JOptionPane.showMessageDialog(null,"Models saved in " + file.toString(),
                                        "Information",JOptionPane.INFORMATION_MESSAGE);

        } //if(success)

        else {

            JOptionPane.showMessageDialog(null,"Models not saved",
                                        "Warning",JOptionPane.WARNING_MESSAGE);

        } //else
        


    } //private void setSurvivalModels()





    public void setNewSurvivalModel(SurvivalModel sm,String currentClassType) {

        File file = FileNameDialog.getOutputFileName("Save",null,null);

        if(file != null) {

            boolean success = smListJBean.setNewSurvivalModel(file,sm);

            if(success) {

                String fileName = file.toString();
                addToTable(currentClassType,fileName);
                smListJBean.addToHashtable(currentClassType,fileName);

            } //if(success)

        } //if(file != null)

        else {

            JOptionPane.showMessageDialog(null,"Model not saved",
                                    "Warning",JOptionPane.WARNING_MESSAGE);

        } //else

    } //public void setNewSurvivalModel(SurvivalModel sm)



} //public class SustainabilityGridsList extends DisplayFrame implements ActionListener
