package iDSS;

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

import iDSS.tables.*;
import iDSS.disp.*;
import iDSS.grids.*;
import iDSS.utils.*;
import iDSS.gridDisp.*;
import iDSS.beans.*;



public class GridManager extends DisplayFrame implements ActionListener {

  private Hashtable gridsHashtable;

  private String currentFileName,currentName;
  private File currentFile;
  private Grid currentGrid;
  private Vector currentRow;

  private JTable gridsTable;
  private JScrollPane gridsTableScrollPane;

  private JButton drawButton;
  private JButton disposeButton;
  private JButton selectButton;
  private JButton pickButton;
  private JButton describeButton;
  private JButton pickServerButton;
  private JButton saveServerButton;

  private boolean ALLOW_ROW_SELECTION = true;

  //private PropertyChangeSupport pcs;
  private String title;
  private int gridType;
  private String serverGridTable;
  private String hashCode;





  public GridManager(String string,int type,String serverGrid,String hashCode) {


    super (string,false,false,false,true,null);
    title = string;
    gridType = type;
    serverGridTable = serverGrid;
    this.hashCode = hashCode;

    if(IDSSAppConstants.debug) {
        System.out.println("GridManager.GridManager(), serverGridTable : " + serverGridTable);
    } //if(IDSSAppConstants.debug)

    //pcs = new PropertyChangeSupport(this);


    gridsHashtable = new Hashtable();
    //gridsHashtable.put(aGrid.getFileName(),aGrid);

    //getContentPane().setLayout(new GridLayout(2,1));
    

  //gridsTablePanel

    JPanel gridsTablePanel = new JPanel();
    gridsTablePanel.setBorder(BorderFactory.createTitledBorder("Grids Fetched So Far"));


    Vector columnNames = new Vector();
    columnNames.add("Grid Name");
    columnNames.add("File Name");

    Vector row = new Vector();

    GeneralTableModel tm = new GeneralTableModel(row,columnNames);

    gridsTable = new JTable(tm);
    gridsTable.setPreferredScrollableViewportSize(new Dimension(300,50));

    gridsTableScrollPane = new JScrollPane(gridsTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    gridsTablePanel.add(gridsTableScrollPane,BorderLayout.CENTER);

  //gridsTablePanel completed


    drawButton = new JButton(IDSSAppConstants.drawButtonText);
    drawButton.addActionListener(this);
    drawButton.setActionCommand(IDSSAppConstants.drawButtonCommand);
    drawButton.setEnabled(false);

    selectButton = new JButton(IDSSAppConstants.selectButtonText);
    selectButton.addActionListener(this);
    selectButton.setActionCommand(IDSSAppConstants.selectButtonCommand);
    selectButton.setEnabled(false);

    disposeButton = new JButton(IDSSAppConstants.disposeButtonText);
    disposeButton.addActionListener(this);
    disposeButton.setActionCommand(IDSSAppConstants.disposeButtonCommand);
    disposeButton.setEnabled(false);

    pickButton = new JButton(IDSSAppConstants.pickButtonText);
    pickButton.addActionListener(this);
    pickButton.setActionCommand(IDSSAppConstants.pickButtonCommand);
    pickButton.setEnabled(true);

    describeButton = new JButton(IDSSAppConstants.describeButtonText);
    describeButton.addActionListener(this);
    describeButton.setActionCommand(IDSSAppConstants.describeButtonCommand);
    describeButton.setEnabled(false);

    pickServerButton = new JButton(IDSSAppConstants.pickServerButtonText);
    pickServerButton.addActionListener(this);
    pickServerButton.setActionCommand(IDSSAppConstants.pickServerButtonCommand);
    pickServerButton.setEnabled(true);

    saveServerButton = new JButton(IDSSAppConstants.saveServerButtonText);
    saveServerButton.addActionListener(this);
    saveServerButton.setActionCommand(IDSSAppConstants.saveServerButtonCommand);
    saveServerButton.setEnabled(false);


    JPanel buttonPanel = new JPanel();
    JPanel buttonPanel1 = new JPanel();
    JPanel buttonPanel2 = new JPanel();

    buttonPanel1.add(drawButton);
    buttonPanel1.add(selectButton);
    buttonPanel1.add(disposeButton);
    buttonPanel1.add(describeButton);
    buttonPanel2.add(pickButton);
    buttonPanel2.add(pickServerButton);
    buttonPanel2.add(saveServerButton);

    buttonPanel.setLayout(new BoxLayout(buttonPanel,BoxLayout.Y_AXIS));
    buttonPanel.add(buttonPanel1);
    buttonPanel.add(buttonPanel2);

    getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
    getContentPane().add(gridsTablePanel);
    getContentPane().add(buttonPanel);


    pack();
    setVisible(true);


    gridsTable.setPreferredScrollableViewportSize(new Dimension(300,40));


    //Detecting row selection

    if (ALLOW_ROW_SELECTION) { // true by default
        ListSelectionModel rowSM = gridsTable.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.");
                    drawButton.setEnabled(false);
                    selectButton.setEnabled(false);
                    disposeButton.setEnabled(false);
                    describeButton.setEnabled(false);
                    saveServerButton.setEnabled(false);


                } else {
                    int selectedRow = lsm.getMinSelectionIndex();
                    System.out.println("Row " + selectedRow
                                       + " is now selected.");

                    drawButton.setEnabled(true);
                    selectButton.setEnabled(true);
                    disposeButton.setEnabled(true);
                    describeButton.setEnabled(true);
                    saveServerButton.setEnabled(true);

                    currentFileName = (String) gridsTable.getValueAt(selectedRow,1);
                    currentFile = new File(currentFileName);
                    currentName = (String) gridsTable.getValueAt(selectedRow,0);
                    currentRow = new Vector();
                    currentRow.add(currentName);
                    currentRow.add(currentFileName);
                    

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



  } //public GridManager();








  public void addToGrids(Grid grid) {

    

    if(grid!=null) {

        if(gridsHashtable.containsKey(grid.getFileName())) {

            currentFileName = grid.getFileName();
            removeFromGrids();

        }//if(gridsHashtable.containsKey(grid.getFileName()))

        gridsHashtable.put(grid.getFileName(),grid);

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

        Vector rowVector = grid.getGridVector();

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

    } //if(grid!=null)

    saveServerButton.setEnabled(false);

  } //public void addToDataSet(aDataSet)





    private void removeFromGrids() {

        drawButton.setEnabled(false);
        selectButton.setEnabled(false);
        disposeButton.setEnabled(false);

        gridsHashtable.remove(currentFileName);

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

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

    } //private void removeFromGrids()





    public void actionPerformed(ActionEvent ae) {


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

            if(IDSSAppConstants.debug)
                DebugWriter.writeDebug(IDSSAppConstants.pickButtonCommand);

            File inFile = FileNameDialog.getInputFileName(title,null,null);

            if (inFile != null) {

                //Grid aGrid = new Grid(gridType+":"+inFile.toString(),gridType,0,inFile);
                Grid aGrid = new Grid(inFile.toString(),gridType,0,inFile);
                if(!aGrid.isRead())
                    aGrid.read();

                addToGrids(aGrid);

            }//if (inFile != null)

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


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

            if(IDSSAppConstants.debug)
                DebugWriter.writeDebug(IDSSAppConstants.drawButtonCommand);

            drawGrid();

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


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

            if(IDSSAppConstants.debug)
                DebugWriter.writeDebug(IDSSAppConstants.disposeButtonCommand);

            removeFromGrids();

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


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

            if(IDSSAppConstants.debug)
                DebugWriter.writeDebug(IDSSAppConstants.selectButtonCommand);

            selectGrid();

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


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

            if(IDSSAppConstants.debug)
                DebugWriter.writeDebug(IDSSAppConstants.saveServerButtonCommand);


            System.out.println(IDSSAppConstants.saveServerButtonCommand);
            saveToServer();

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


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

            if(IDSSAppConstants.debug)
                DebugWriter.writeDebug(IDSSAppConstants.pickServerButtonCommand);

            System.out.println(IDSSAppConstants.pickServerButtonCommand);
            pickFromServer();

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



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

            if(IDSSAppConstants.debug)
                DebugWriter.writeDebug(IDSSAppConstants.describeButtonCommand);

            System.out.println(IDSSAppConstants.pickServerButtonCommand);
            describe();

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


    } //public void actionPerformed(ActionEvent ae)





    private void describe() {

        currentGrid = (Grid) gridsHashtable.get(currentFileName);

        if (!currentGrid.isRead()) {
            currentGrid.read();
        }


        DocumentDisplay aDocDisplay =
            new DocumentDisplay ("Describing :" + currentGrid.getName(),currentGrid.showdescription(),"text/HTML");

        firePropertyChange(IDSSAppConstants.addToModelView,null,aDocDisplay);

    } //private void describe()












    private void saveToServer() {


        GridsJBean gridsJBean = new GridsJBean();
        gridsJBean.setEjbName(IDSSAppConstants.gridsBean,serverGridTable);

        currentGrid = (Grid) gridsHashtable.get(currentFileName);

        if(currentGrid != null) {

            gridsJBean.saveOnServer(currentGrid,IDSSAppConstants.ip,currentFileName);

        } //if(currentGrid != null)


    } //private void saveToServer()





    private void pickFromServer() {

        GridsJBean gridsJBean = new GridsJBean();
        gridsJBean.setEjbName(IDSSAppConstants.gridsBean,serverGridTable);

        Collection grids = gridsJBean.findAll();

        if (grids != null) {

            Iterator i = grids.iterator();
            while(i.hasNext()) {

                Grid g = (Grid)i.next();
                g.setType(gridType);
                addToGrids(g);

            } //while(i.hasNext())

        } //if (grids != null)

        else {

            JOptionPane.showMessageDialog(null,"No grid found on server",
                            "Error",JOptionPane.ERROR_MESSAGE);

        }//

    } //public void pickFromServer()








    public void selectGrid() {

        currentGrid = (Grid) gridsHashtable.get(currentFileName);

        if(currentGrid != null) {
            System.out.println("GridManager.selectGrid(), currentGrid not null");
            System.out.println("currentGrid.getName() : " + currentGrid.getName());
            Vector v = new Vector();
            v.add(hashCode);
            v.add(currentGrid);
            firePropertyChange(IDSSAppConstants.addGridToModel,null,v);
        } //if(currentGrid != null)

        else {
            if(IDSSAppConstants.debug) {

                DebugWriter.writeDebug("GridManager.selectGrid(), currentGrid = null");
                System.out.println("GridManager.selectGrid(), currentGrid = null");

            } //if(IDSSAppConstants.debug)

        }//else


    } //public void select()







/**

  public void actionPerformed(ActionEvent ae) {

    if (ae.getActionCommand().equals("draw")) {

        System.out.println("Draw the grid");

        drawGrid();

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


    else if (ae.getActionCommand().equals("dispose")) {

        System.out.println("Dispose the grid");
        removeFromGrids();

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



    else if (ae.getActionCommand().equals("select")) {

        System.out.println("Select the grid for simulation");
        selectGrid();

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




    else if (ae.getActionCommand().equals("gridView")) {

        System.out.println("Get a new grid");
        //getNewGrid();
        viewGrid();

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


    else if (ae.getActionCommand().equals("describe")) {

        System.out.println("Describe grid");
        currentGrid = (Grid) gridsHashtable.get(currentFileName);
        //currentGrid.describe();

        DocumentDisplay aDocDisplay =
            new DocumentDisplay ("Describing :" + currentGrid.getName(),currentGrid.showdescription(),"text/HTML");

        addToDesktop(aDocDisplay);



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



  } //public void actionPerformed(ActionEvent ae)


**/







    private void drawGrid() {

        if(IDSSAppConstants.debug)
            System.out.println("GridManager.drawGrid(), file : " + currentFileName);

        currentGrid = (Grid) gridsHashtable.get(currentFileName);

        if (!currentGrid.isRead()) {
            currentGrid.read();
        }


        SurfaceColor sc = new SurfaceColor(currentGrid.getName(),currentGrid.getZMin(),
                                        currentGrid.getZMax(),SurfaceColor.DEM);

        GridDisplay gridDisplay = new GridDisplay(currentGrid.getName());

        currentGrid.draw(gridDisplay,sc);

        firePropertyChange(IDSSAppConstants.addToModelView,null,gridDisplay);

        ImageDisplay legendFrame = new ImageDisplay(currentGrid.getName()+
                                        ":Legend",sc.getLegendWidth(),
                                        sc.getLegendHeight());

        firePropertyChange(IDSSAppConstants.addToModelView,null,legendFrame);
        sc.drawLegend(legendFrame);



    } //private void drawGrid()









/**




    private void viewGrid() {

        GridView gridView = new GridView(aFrame,aDesktopPane,gridsHashtable);
        //iDSS.GView.GridView gridView = new GridView(aFrame,aDesktopPane,gridsHashtable);
        addToDesktop(gridView);

    } //private void viewGrid()


***/




/**


**/



/***


    private void addToDesktop(JComponent c) {

        aDesktopPane.add(c);
        aDesktopPane.setPosition(c,0);
        aFrame.setContentPane(aDesktopPane);

    }






***/



    public String toString() {

        return "DisplayFrame: " + title;

    } //public String toString()


} //public class GridManager extends DisplayFrame



