/*
 * Created on Jan 25, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package gov.nasa.jsc.plum;
import gov.nasa.jsc.plum.PlumUtil.DatabaseWindow;
import gov.nasa.jsc.plum.PlumUtil.PlumUtilities;
import gov.nasa.jsc.plum.PlumUtil.RowPanel;
import gov.nasa.jsc.plum.PlumUtil.Updateable;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

/**
 * @author randrews
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class StationWindow extends JFrame implements ActionListener, Updateable{

    JTree tree;
    Connection conn;
    JButton newbtn,delbtn;
    DatabaseWindow parent;
    
    public StationWindow(Connection conn, DatabaseWindow parent){
        super("Rack Data");
        this.parent=parent;
        this.conn=conn;
        
        StationTreeNode root=new StationTreeNode("Station",null);
        tree=new JTree(root);
        updateWindow();
        tree.expandPath(new TreePath(root));
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        getContentPane().setLayout(new BorderLayout());
        
        JScrollPane scroll=new JScrollPane(tree);
        getContentPane().add(scroll,BorderLayout.CENTER);
        
        MouseListener ml = new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                lightButtons();
                if(e.getClickCount() == 2)
                    handleSelection();
            }
        };
        tree.addMouseListener(ml);
        
        JPanel buttons=new JPanel();
        buttons.setLayout(new BorderLayout());
        newbtn=new JButton("New Rack");
        delbtn=new JButton("Delete rack");
        newbtn.addActionListener(this);
        delbtn.addActionListener(this);
        buttons.add(newbtn,BorderLayout.SOUTH);
        buttons.add(delbtn,BorderLayout.NORTH);
        getContentPane().add(buttons,BorderLayout.SOUTH);
        
        pack();
        
        parent.addWindow(this);
    }
        
    public void lightButtons(){
        StationTreeNode node=(StationTreeNode) tree.getLastSelectedPathComponent();
        if(node==null)return;
        ResultSet row=node.getRow();
        switch(tree.getSelectionPath().getPathCount())
        {
        case 1:newbtn.setEnabled(false);delbtn.setEnabled(false);break; // Root
        case 2:newbtn.setEnabled(true);delbtn.setEnabled(false);break; // Modules
        case 3:newbtn.setEnabled(false);delbtn.setEnabled(true);break; // Racks
        case 4:newbtn.setEnabled(false);delbtn.setEnabled(false);break; // Locations
        }

    }
    
    public void handleSelection(){
        StationTreeNode node=(StationTreeNode) tree.getLastSelectedPathComponent();
        if(node==null)return;
        ResultSet row=node.getRow();
        if(row==null)return; // We've selected the root node, which has no row assoc. with it.
        String tblname="";
        switch(tree.getSelectionPath().getPathCount())
        {
        case 2:tblname="modules";break;
        case 3:tblname="racks";break;
        case 4:tblname="locations";break;
        }
        RowPanel panel=new RowPanel(row,conn,tblname,"idx");
        panel.setParent(parent);
        JFrame frame=new JFrame(node.getUserObject().toString());
        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(panel,BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent event) {
        if(event.getSource()==newbtn)
        {
            StationTreeNode node=(StationTreeNode) tree.getLastSelectedPathComponent();
            if(node==null || tree.getModel().getRoot()!=node.getParent()) // We haven't got a module selected
                return;
            try {
                AddRackDialog add=new AddRackDialog(conn,parent,this,node.getRow().getString("acronym"));
                add.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else if(event.getSource()==delbtn)
        {
            StationTreeNode node=(StationTreeNode) tree.getLastSelectedPathComponent();
            if(node==null || tree.getModel().getRoot()!=node.getParent().getParent()) // We haven't got a rack selected
                return;
            try {
                int confirm=JOptionPane.showConfirmDialog(this,
                        "Are you sure you want to delete "+node.getRow().getString("acronym")+"?",
                        "Confirm Delete",
                        JOptionPane.YES_NO_OPTION);
                if(confirm==JOptionPane.YES_OPTION)
                {
                    PlumUtilities.deleteRack(conn,node.getRow().getInt("idx"));
                    parent.updateWindows();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }            
        }
    }
    
    public void finalize(){
        parent.removeWindow(this);
    }
    
    public void updateWindow() {
        try{
            StationTreeNode root=(StationTreeNode) tree.getModel().getRoot();
            synchronized(root)
            {
                root.removeAllChildren();
                ResultSet modules=conn.createStatement().executeQuery("select * from modules");
                while(modules.next())
                {
                    int modidx=modules.getInt("idx");
                    ResultSet modres=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE).executeQuery("select * from modules where name=\""+modules.getString("name")+"\"");
                    modres.next();
                    StationTreeNode mod=new StationTreeNode(modules.getString("name"),modres);
                    root.add(mod);
                    ResultSet racks=conn.createStatement().executeQuery("select racks.* from racks,locations where racks.location=locations.idx and locations.module="+modidx);
                    while(racks.next())
                    {
                        ResultSet rackres=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE).executeQuery("select * from racks where acronym=\""+racks.getString("acronym")+"\"");
                        rackres.next();
                        StationTreeNode rack=new StationTreeNode(racks.getString("acronym"),rackres);
                        mod.add(rack);
                        ResultSet loc=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE).executeQuery("select * from locations where idx="+racks.getInt("location"));
                        loc.next();
                        rack.add(new StationTreeNode(loc.getString("name"),loc));
                    }
                }
                ((DefaultTreeModel)(tree.getModel())).setRoot(root);
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}
