// file: BugMenu.java
//

// import java libraries
//
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

public class VarmintPanel extends JPanel implements ActionListener, 
						    MouseListener,
						    KeyListener {

    // declare global variables
    // 
    public static final String DEFAULT_QUERY = 
	new String("select * from bug_list where Status='open'\n");

    SearchMenu searchMenu = null;
    BugSearch bugSearch = null;
    JPanel panelAndSearch = null;
    VarmintDB database = null;

    // title font size and style for the viewport border
    //
    Font currentFont = null;
    Font newFont = null;
    // maximum font size for the componets
    //
    private static final int MAX_FONT_SIZE = (int)12;

    // create a file chooser for the saving and deleting of queries
    //
    JFileChooser queryChooser = null;
    File queryFile = null;
    String user = null;
    GotoFrame gotoFrame = null;

    JFrame parent_frame = null;

    public static boolean is_applet = false;
    
    // ------------------------------------------------------------------
    //
    // declare class constructors
    //
    // ------------------------------------------------------------------
    // method: VarmintPanel
    //
    // arguments: none
    // returns  : none
    //
    // default class constructor
    //
    public VarmintPanel(String use, boolean is_applet_a, JFrame parent) {

	parent_frame = parent;

	is_applet = is_applet_a;

	database = new VarmintDB();

	// create the font that will go everywhere
	//
	currentFont = this.getFont();
        newFont = new Font(currentFont.getName(), Font.PLAIN, MAX_FONT_SIZE);

	GridBagLayout gridbag = new GridBagLayout();
	this.setLayout(gridbag);	
	GridBagConstraints c = new GridBagConstraints();

	// pass the username along to the inside
	//
	user = use;

	// create all panels
	//
	searchMenu   = new SearchMenu(this);
	searchMenu.setMinimumSize(new Dimension(100, 30));
	bugSearch  = new BugSearch(this);
	bugSearch.setMinimumSize(new Dimension(500,500));

	
	// place the edit pane
	//
	c.gridx = 0;
	c.gridy = 0;
	c.gridwidth = GridBagConstraints.REMAINDER;
	c.gridheight = 1;
	c.weightx = 1;
	c.weighty = 0;
	c.anchor = GridBagConstraints.NORTHWEST;
	c.fill = GridBagConstraints.HORIZONTAL;
	c.insets = new Insets(0,0,0,0);
	gridbag.setConstraints(searchMenu, c);
	this.add(searchMenu);


	c.gridx = 0;
	c.gridy = 1;
	c.gridwidth = GridBagConstraints.REMAINDER;
	c.gridheight = GridBagConstraints.REMAINDER;
	c.weightx = 1;
	c.weighty = 1;
	c.anchor = GridBagConstraints.NORTHWEST;
	c.fill = GridBagConstraints.BOTH;
	c.insets = new Insets(5,5,5,5);
	gridbag.setConstraints(bugSearch, c);
	this.add(bugSearch);

	if (!is_applet) {
	    queryChooser = new JFileChooser();
	    queryChooser.setFont(newFont);
	}
					
    }

    //-------------------------------------------------------------------
    //
    //  Mouse Handler Methods
    //
    //-------------------------------------------------------------------

    public void mouseClicked(MouseEvent l) {
	
	if (l.getClickCount() == 2) {
	    
	    int select = bugSearch.bugTable.table.getSelectedRow();
	    String bugNum = (String)bugSearch.
		bugTable.table.getValueAt(select, 3);
	    String dbase = (String)bugSearch.
		bugTable.table.getValueAt(select, 4);
	    
	    loadBug(Integer.parseInt(bugNum), dbase);
	}
    }

    public void mouseEntered(MouseEvent l) {
    }
    public void mousePressed(MouseEvent l) {
    }
    public void mouseReleased(MouseEvent l) {
    }
    public void mouseExited(MouseEvent l) {
    }

    
    //---------------------------------------------------------------
    //
    //   Action Handler Methods
    //
    //---------------------------------------------------------------
    
    // method: actionPerformed
    //
    // arguments:
    //    ActionEvent e: event that was fired
    //
    // return   : none
    //
    // listens for actions taking place on the components
    //
    public void actionPerformed(ActionEvent e) {


	if (e.getActionCommand().equals("New Bug")) {
       	    
	    actionNew();
	}

	if (e.getActionCommand().equals("Exit")) {
	       
	    actionExit();
	}

	if (e.getActionCommand().equals("Find Bug")) {
	
	    actionGoto();
	}

	if (e.getActionCommand().equals("Submit")) {
	    
	    actionSubmit();
	}

	if (e.getActionCommand().equals("New")) {

	    actionNewQuery();
	}

	if (e.getActionCommand().equals("Save")) {

	    actionSaveQuery();
	    
	}	

	if (e.getActionCommand().equals("Save Query")) {


	    
	}	

	if (e.getActionCommand().equals("Configuration")) {
	    actionConfiguration();
	}

	if (e.getActionCommand().equals("Unlock All")) {
	    actionUnlockAll();
	}

	if (e.getActionCommand().equals("By Owner")) {
	    actionRunStat("Owner");
	}	

	if (e.getActionCommand().equals("By Status")) {
	    actionRunStat("Status");
	}

	if (e.getActionCommand().equals("By Database")) {
	    actionRunStat("DBase");
	}

	if (e.getActionCommand().equals("By Class")) {
	    actionRunStat("Class");
	}

	if (e.getActionCommand().equals("By Priority")) {
	    actionRunStat("Priority");
	}

	if (e.getActionCommand().equals("By Severity")) {
	    actionRunStat("Severity");
	}

	if (e.getActionCommand().equals("By Due Date")) {
	    actionRunStat("Due");
	}

	if (e.getActionCommand().equals("By Resolution")) {
	    actionRunStat("Resolution");
	}

	if (e.getActionCommand().equals("By Inspected By")) {
	    actionRunStat("InspectedBy");
	}

	if (e.getActionCommand().equals("By Environment")) {
	    actionRunStat("Environment");
	}

	if (e.getActionCommand().equals("By Test Case")) {
	    actionRunStat("TestCase");
	}

	if (e.getActionCommand().equals("By Component")) {
	    actionRunStat("Component");
	}

	if (e.getActionCommand().equals("By Opener")) {
	    actionRunStat("OpenedBy");
	}

	if (e.getActionCommand().equals("By Resolver")) {
	    actionRunStat("ResolvedBy");
	}

	if (e.getActionCommand().equals("By Closer")) {
	    actionRunStat("ClosedBy");
	}

	if (e.getActionCommand().equals("Load")) {
	    
	    actionLoadQuery();
	}
	
	if (e.getActionCommand().equals("Execute")) {

	    actionExecuteQuery();
	}

	if (e.getActionCommand().equals("SQL")) {

	    actionDisplaySQL();
	}

	if (e.getActionCommand().equals("Generate Query")) {

	    BugQuery.setQueryString("");
	    BugQuery.setQueryModify(false);
	    BugQuery.setQueryNum(-1);

	    System.out.println("Generate the Query");

	    String query = searchMenu.generateQuery();

	    bugSearch.bugQuery.queryEntry.setText(query);
	    
	}

    }

    //----------------------------------------------------------------
    //
    //  Utitlity Methods  -- functions called only by others and not
    //                       directly by a user action
    //
    //----------------------------------------------------------------


    private void loadBug(int bugNum, String dbase) {
	
	
	Bug loadBug = database.getBug(dbase, bugNum); 
	
	final BugPanel bugPanel  = new BugPanel(newFont, 
						new String("" + bugNum),
						2, loadBug, database, user);
	
	// listen for window closing events
	//
	bugPanel.addWindowListener(new WindowAdapter() {
		public void windowClosing(WindowEvent e) 
		{bugPanel.dispose();}
	    });
	
	bugPanel.setFont(newFont);
	
	// resize and set the frame dimensions
	//
	bugPanel.pack();
	
	// center the frame to the screen
	//
	Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); 
	Rectangle frameDim = bugPanel.getBounds(); 
	bugPanel.setLocation((screenDim.width - frameDim.width) / 2 + 50,
			     (screenDim.height - 
			      frameDim.height) / 2 + 50); 
	
	// display the frame
	//
	bugPanel.setVisible(true);
    }
    
    //---------------------------------------------------------------------
    //
    //  Action Methods
    //        
    //---------------------------------------------------------------------

    //--------------------------------
    //
    //  Method:  actionExit()
    //  Desciption:  Exits the program
    //
    //--------------------------------
    private void actionExit() {
	
	// close the application
	//
	if (!is_applet) {
	    System.exit(0);
	} else {
	    parent_frame.dispose();
	}
    }

    private void actionConfiguration() {
	
	System.out.println("running config");
	
	final VConfigPanel cfgPanel = new VConfigPanel(newFont, database);


	// listen for window closing events
	//
	cfgPanel.addWindowListener(new WindowAdapter() {
		public void windowClosing(WindowEvent e) 
		{cfgPanel.dispose();}
	    });
	
	cfgPanel.setFont(newFont);
	
	// resize and set the frame dimensions
	//
	cfgPanel.pack();
	
	// center the frame to the screen
	//
	Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); 
	Rectangle frameDim = cfgPanel.getBounds(); 
	cfgPanel.setLocation((screenDim.width - frameDim.width) / 2 + 50,
			     (screenDim.height - 
			      frameDim.height) / 2 + 50); 
	
	// display the frame
	//
	cfgPanel.setVisible(true);
	
    }

    private void actionUnlockAll() {
	
	System.out.println("running unlock");
	
	database.unLockAll();
    }
	

    private void actionNew() {

	Bug newbug = new Bug();
	
	final BugPanel bugPanel  = new BugPanel(newFont, "new", 1, newbug, 
						database, user);
	
	// listen for window closing events
	//
	bugPanel.addWindowListener(new WindowAdapter() {
		public void windowClosing(WindowEvent e) 
		{bugPanel.dispose();}
	    });
	
	bugPanel.setFont(newFont);
	
	// resize and set the frame dimensions
	//
	bugPanel.pack();
	
	// center the frame to the screen
	//
	Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); 
	Rectangle frameDim = bugPanel.getBounds(); 
	bugPanel.setLocation((screenDim.width - frameDim.width) / 2 + 50,
			     (screenDim.height - 
			      frameDim.height) / 2 + 50); 
	
	// display the frame
	//
	bugPanel.setVisible(true);

	
	
    }
    
    private void actionGoto() {
	
	gotoFrame = new GotoFrame(this);
	
	// resize and set the frame dimensions
	//
	gotoFrame.pack();
	
	// center the frame to the screen
	//
	Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); 
	Rectangle frameDim = gotoFrame.getBounds(); 
	gotoFrame.setLocation((screenDim.width - frameDim.width) / 2 + 50,
			      (screenDim.height - 
			       frameDim.height) / 2 + 50); 
	
	// display the frame
	//
	gotoFrame.setVisible(true);
	
    }

    private void actionRunStat(String field) {

	String query = bugSearch.bugQuery.queryEntry.getText();

	final VStatistics stat = new VStatistics(newFont, field, 
						 query, database);

	// listen for window closing events
	//
	stat.addWindowListener(new WindowAdapter() {
		public void windowClosing(WindowEvent e) 
		{stat.dispose();}
	    });
	
	stat.setFont(newFont);
	
	// resize and set the frame dimensions
	//
	// stat.pack();
	
	// center the frame to the screen
	//
	Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); 
	Rectangle frameDim = stat.getBounds(); 
	stat.setLocation((screenDim.width - frameDim.width) / 2 + 50,
			 (screenDim.height - 
			  frameDim.height) / 2 + 50); 
	
	// display the frame
	//
	stat.setVisible(true);
    }

    private void actionSubmit() {

	String bugNum = gotoFrame.bugEntry.getText();
	String dbase = (String)gotoFrame.dbase.getSelectedItem();
	gotoFrame.dispose();
	loadBug(Integer.parseInt(bugNum), dbase);

    }
    
    private void actionNewQuery() {
	// clears out the table
	//
	for (int i = (bugSearch.bugTable.readOnlyTable.getRowCount() - 1);
	     i >= 0; i-- ) {
	    bugSearch.bugTable.readOnlyTable.removeRow(i);
	}
	
	// clear out the query box
	//
	bugSearch.bugQuery.queryEntry.setText(DEFAULT_QUERY);
	
	BugQuery.setQueryString("");
	BugQuery.setQueryModify(false);
	BugQuery.setQueryNum(-1);

	for (int i=0; i < 12; i++) {
	    searchMenu.clearSubMenu(i);
	}
	
    }

    private void actionSaveQuery() {


	VarmintQuery query = new VarmintQuery(database, user);
	String import_query = bugSearch.bugQuery.queryEntry.getText();
	query.SaveQuery(import_query, this);
	
    }

    private void actionLoadQuery() {
	
	Vector queries = database.loadQueries(user);
	for(int i = 0; i < queries.size(); i++) {
	    
	    Vector individual = (Vector)queries.get(i);
	    for (int j = 0; j < individual.size(); j++) {
		System.out.println(j + (String)individual.get(j));
	    }
	}
    }

    public void actionExecuteQuery() {

	// clears out the table
	//
	for (int i = (bugSearch.bugTable.readOnlyTable.getRowCount() - 1);
	     i >= 0; i-- ) {
	    bugSearch.bugTable.readOnlyTable.removeRow(i);
	}
	
	// gets the list of bugs that satisfy the query
	//
	Vector bugList = new Vector(10,10);

	bugList = 
	    database.getBugList(bugSearch.bugQuery.queryEntry.getText());
	
	BugQuery.setQueryNum(bugList.size());
	BugQuery.updateTitle();

	// takes the bug information and crams it into the table
	//
	for (int i = 0; i < bugList.size(); i++) {
	    Vector vec1 = new Vector(7,7);
	    
	    if(((Bug)bugList.get(i)).getField("OpenDate") != null) {
	    	vec1.add(((Bug)bugList.get(i)).getField("OpenDate"));
	    }
	    else
	    	vec1.add(new String(""));
	    
	    //vec1.add(new String(""));

	    if(((Bug)bugList.get(i)).getField("ModifyDate") != null) {
	    	vec1.add(((Bug)bugList.get(i)).getField("ModifyDate"));
	    }
	    else 
	    	vec1.add(new String(""));
	    
	    // format the status element for display
	    //
	    String status = ((Bug)bugList.get(i)).getField("Status");
	    
	    if (status != null) {
		if (status.toLowerCase().equals("resolved"))
		    status = "R";
		else if (status.toLowerCase().equals("open")) 
		    status = "O";
		else if (status.toLowerCase().equals("closed"))
		    status = "C";
	    }

	    vec1.add(status);
	    vec1.add(((Bug)bugList.get(i)).getField("BugNumber"));
	    vec1.add(((Bug)bugList.get(i)).getField("DBase"));

	    // format the priority element for display
	    //
	    String priority = ((Bug)bugList.get(i)).getField("Priority");
	    
	    if (priority != null) {
		if (priority.toLowerCase().equals("high"))
		    priority = "H";
		else if (priority.toLowerCase().equals("medium")) 
		    priority = "M";
		else if (priority.toLowerCase().equals("low"))
		    priority = "L";
	    }
	    vec1.add(priority);
	    
	    // format the severity element for display
	    //
	    String severity = ((Bug)bugList.get(i)).getField("Severity");
	    
	    if (severity != null) {
		if (severity.toLowerCase().equals("critical"))
		    severity = "C";
		else if (severity.toLowerCase().equals("serious")) 
		    severity = "S";
		else if (severity.toLowerCase().equals("non-critical"))
		    severity = "N";
	    }
	    vec1.add(severity);

	    vec1.add(((Bug)bugList.get(i)).getField("Owner"));
	    vec1.add(((Bug)bugList.get(i)).getField("Title"));

	    if(!((Bug)bugList.get(i)).getField("BugNumber").equals("0"))
		bugSearch.bugTable.readOnlyTable.addRow(vec1);
	}
	bugSearch.bugTable.grabFocus();
    }

    private void actionDisplaySQL() {

	// get a handle on the SQL check box
	//
     	JCheckBoxMenuItem sqlCheck = 
	    (JCheckBoxMenuItem)((JMenu)searchMenu.menu_bar.getComponent(2)).
		getMenuComponent(0);

	// determine if the box is checked.  Based on its value, make
	// the query box visible
	//
	if (sqlCheck.getState()) {
	    bugSearch.bugQuery.mountingPanel.setVisible(true);
	}
	else 
	    bugSearch.bugQuery.mountingPanel.setVisible(false);

	// force the frame to redo its layout so everything is 
	// displayed correctly
	//
	validate();
    }

    public void keyTyped(KeyEvent evt) {

    }
    public void keyReleased(KeyEvent e) {
    }
    
    public void keyPressed(KeyEvent evt) {
    
	if (evt.getModifiers() == java.awt.event.ActionEvent.CTRL_MASK) { 
	    
	    switch (evt.getKeyCode()) { 
	    case java.awt.event.KeyEvent.VK_N: // New Bug
		actionNew();
		break; 
		
	    case java.awt.event.KeyEvent.VK_G: // Goto Bug 
		actionGoto();
		break; 
		
	    case java.awt.event.KeyEvent.VK_X: // Execute Query 
		actionExecuteQuery();
		break; 		
		
	    case java.awt.event.KeyEvent.VK_V: // Save Query 
		actionSaveQuery();
		break; 
	    
	    case java.awt.event.KeyEvent.VK_L: // Load Query 
		actionLoadQuery();
		break; 

	    case java.awt.event.KeyEvent.VK_W: // New Query 
		actionNewQuery();
		break; 
		
	    case java.awt.event.KeyEvent.VK_C: // Exit Program 
		actionExit();
		break; 
	    
	    }
   	}
    }
}













