/*
 Copyright (c) 1997 by Columbia University. All rights reserved.
 */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import tea.set.*;
import tjt.util.MsgDialog;
import java.net.*;
import java.util.*;
import symantec.itools.awt.TabPanel;

/** 
 * GUI Frame that displays the results of the different types of tests
 * performed with ping and traceroute. For graphing it uses a Graph
 * object from the TeaSet Widget Collection. It also uses a TabPanel
 * object from Symantec Corporation.
 * @version 1.0 31 Aug 1998
 * @author Terrence Truta
 */
public class DisplayGUI extends Frame
{
	public DisplayGUI(NetTest ns)
	{
		// This code is automatically generated by Visual Cafe when you add
		// components to the visual environment. It instantiates and initializes
		// the components. To modify the code, only use code syntax that matches
		// what Visual Cafe can generate, or Visual Cafe may be unable to back
		// parse your Java file into its visual environment.
			//{{INIT_CONTROLS
		setLayout(null);
		setVisible(false);
		setSize(660,443);
		setBackground(new Color(12632256));
		tabPanel1 = new symantec.itools.awt.TabPanel();
		//try {
			java.lang.String[] tempString = new java.lang.String[4];
			tempString[0] = new java.lang.String("Delay Graph");
			tempString[1] = new java.lang.String("Delay Data");
			tempString[2] = new java.lang.String("Loss Graph");
			tempString[3] = new java.lang.String("Loss Data");
			tabPanel1.setPanelLabels(tempString);
		//}
		//catch(java.beans.PropertyVetoException e) { }
		//try {
			tabPanel1.setTabsOnBottom(true);
		//}
		//catch(java.beans.PropertyVetoException e) { }
		//try {
			tabPanel1.setCurrentPanelNdx(0);
		//}
		//catch(java.beans.PropertyVetoException e) { }
		tabPanel1.setBounds(12,12,636,384);
		add(tabPanel1);
		tpanel1 = new java.awt.Panel();
		tpanel1.setLayout(null);
		tpanel1.setVisible(false);
		tpanel1.setBounds(12,16,612,340);
		tabPanel1.add(tpanel1);
		cmbGraphType = new java.awt.Choice();
		cmbGraphType.addItem("Bar");
		cmbGraphType.addItem("Line");
		cmbGraphType.addItem("Pie");
		try {
			cmbGraphType.select(1);
		}
		catch (IllegalArgumentException e) { }
		tpanel1.add(cmbGraphType);
		cmbGraphType.setBounds(118,4,134,32);
		label1 = new java.awt.Label("Graph Type:");
		label1.setBounds(18,8,96,24);
		tpanel1.add(label1);
		lblCaption1 = new java.awt.Label("Click on the graph to see the host name and IP address");
		lblCaption1.setBounds(10,308,476,22);
		tpanel1.add(lblCaption1);
		//graph = new java.awt.Panel();
		graph = new Graph();
		graph.setLayout(null);
		graph.setBounds(14,40,586,263);
		graph.setBackground(new Color(12632256));
		tpanel1.add(graph);
		label2 = new java.awt.Label("ms");
		label2.setBounds(2,112,20,23);
		graph.add(label2);
		tpanel2 = new java.awt.Panel();
		tpanel2.setLayout(new BorderLayout(0,0));
		tpanel2.setVisible(false);
		tpanel2.setBounds(12,16,612,340);
		tabPanel1.add(tpanel2);
		txtDelayData = new java.awt.TextArea();
		txtDelayData.setBounds(0,0,612,340);
		tpanel2.add("Center", txtDelayData);
		tpanel3 = new java.awt.Panel();
		tpanel3.setLayout(null);
		tpanel3.setVisible(false);
		tpanel3.setBounds(12,16,612,340);
		tabPanel1.add(tpanel3);
		tpanel3.setEnabled(false);
		cmbGraphType2 = new java.awt.Choice();
		cmbGraphType2.addItem("Bar");
		cmbGraphType2.addItem("Line");
		cmbGraphType2.addItem("Pie");
		try {
			cmbGraphType2.select(0);
		}
		catch (IllegalArgumentException e) { }
		tpanel3.add(cmbGraphType2);
		cmbGraphType2.setBounds(118,4,134,32);
		label3 = new java.awt.Label("Graph Type:");
		label3.setBounds(18,8,96,24);
		tpanel3.add(label3);
		lblCaption2 = new java.awt.Label("Click on the graph to see the host name and IP address");
		lblCaption2.setBounds(10,308,476,22);
		tpanel3.add(lblCaption2);
		//graphLoss = new java.awt.Panel();
		graphLoss= new Graph();
		graphLoss.setLayout(null);
		graphLoss.setBounds(14,40,590,263);
		graphLoss.setBackground(new Color(12632256));
		tpanel3.add(graphLoss);
		label5 = new java.awt.Label("");
		label5.setBounds(2,112,20,23);
		graphLoss.add(label5);
		tpanel4 = new java.awt.Panel();
		tpanel4.setLayout(new BorderLayout(0,0));
		tpanel4.setBounds(12,16,612,340);
		tabPanel1.add(tpanel4);
		tpanel4.setEnabled(false);
		txtLossData = new java.awt.TextArea();
		txtLossData.setBounds(0,0,612,340);
		tpanel4.add("Center", txtLossData);
		btnClose = new java.awt.Button();
		btnClose.setLabel("Close");
		btnClose.setBounds(556,404,83,32);
		btnClose.setBackground(new Color(12632256));
		add(btnClose);
		setTitle("NetTest");
		//}}

		txtDelayData.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
		txtLossData.setFont(new Font("MonoSpaced", Font.PLAIN, 12));

		//{{INIT_MENUS
		//}}

		//{{REGISTER_LISTENERS
		SymWindow aSymWindow = new SymWindow();
		this.addWindowListener(aSymWindow);
		SymAction lSymAction = new SymAction();
		SymItem lSymItem = new SymItem();
		cmbGraphType.addItemListener(lSymItem);
		cmbGraphType2.addItemListener(lSymItem);
		btnClose.addActionListener(lSymAction);
		//}}

		 graph.addItemListener(new GraphItemListener());
     //graph.addMouseListener(new GraphMouseListener());  
		 graph.setStyle(Graph.LINE);

		 graphLoss.addItemListener(new GraphItemListener());
     //graph.addMouseListener(new GraphMouseListener());  
		  graphLoss.setStyle(Graph.BAR);

		 this.app = ns;

		//NetTest logic
				//tw.execute();
		
		//gui.setData(tw.getXData(), tw.getYData());
	}

    /**
     * Shows or hides the component depending on the boolean flag b.
     * @param b  if true, show the component; otherwise, hide the component.
     * @see java.awt.Component#isVisible
     */
    public void setVisible(boolean b)
	{
		if(b)
		{
			setLocation(50, 50);
		}
		super.setVisible(b);
	}

	static public void main(String args[])
	{
		(new DisplayGUI(null)).setVisible(true);
	}

	/** Displays average delay and packet loss data in graphs and textually.
	 * Called by executeTracert() and executeThoroughTracert() methods.
	 * @param chartdata - Object that holds all the data from the traceroute
	 * and ping outputs.
	 */
	public void displayData(ChartData chartdata) {
		 int i;
		 
		 //set Delay data
		 hostY = chartdata.avg;
		 String[] hostX = new String[chartdata.hops];
		 debugPrint("chartdata.hops = " + chartdata.hops);
		 for (i = 0; i < chartdata.hops; i++) 
			 hostX[i] = new String(Integer.toString(i+1));

		 yx = new DataSet(false);
         yx.setData(hostX);

		 graph.setValues(yx.getData(), (new DataSet(hostY)).getData());

		 txtDelayData.setText(""); //clear the box
		 txtDelayData.setText("Avg Delay\t\tHost\n" + 
                                 "---------\t\t----"); 
		 debugPrint("traceout size is " + chartdata.trace_out.size() );
		 for (i = 0; i < chartdata.trace_out.size(); i++) {
				if (chartdata.hostName[i] == null) break;
				txtDelayData.append("\n" + chartdata.avg[i] + 
													"\t\t\t" + chartdata.hostName[i]);
		 }
		 txtDelayData.append("\n\nTraceroute Output:\n");
		 for (i = 0; i < chartdata.trace_out.size(); i++) 
				txtDelayData.append((String)chartdata.trace_out.elementAt(i) + "\n");
			

     hostY2 = chartdata.packetLoss;
     //hostX2 = hostX;
     yx2 = new DataSet(false);
     yx2.setData(hostX);
     graphLoss.setValues(yx2.getData(), (new DataSet(hostY2)).getData());
     
     txtLossData.setText("Packets Lost\t\tHost\n" + 
                         "------------\t\t----"); 
     debugPrint("traceout size is " + chartdata.trace_out.size() );
     for (i = 0; i < chartdata.trace_out.size(); i ++)  {
			 if (chartdata.hostName[i] == null) break;
    	 txtLossData.append("\n" + chartdata.packetLoss[i] + 
    		                  "\t\t\t" + chartdata.hostName[i]);
		 }
     tpanel3.setEnabled(true);
     tpanel4.setEnabled(true);
		 lblCaption1.setText("Click on the graph to see the host name and IP address");
		 lblCaption2.setText("Click on the graph to see the host name and IP address");
		 this.time = null; //set time array = null since the graph isn't
											 //showing data from the continuous summary test

     this.chartdata = chartdata;    
	}

	/** Displays the average delay and losses from the continuous ping operation.
	 *  It is called only after all the data is collected. 
	 * @param avg - The average delay experienced over time to the choosen host
	 * @param loss - The losses experienced over time to the choosen host
	 * @param time - The time values when the ping program was executed
	 */
	public void displaySummaryData(int[] avg, int[] loss, long[] time) {
	   int i;
		 Date d;
		 //set Delay data
		 hostY = avg;
		 String[] hostX = new String[avg.length];
		 debugPrint("avg.length = " + avg.length);
		 for (i = 0; i < avg.length; i++) 
			 hostX[i] = new String(Integer.toString(i+1));

		 yx = new DataSet(false);
         yx.setData(hostX);

		 graph.setValues(yx.getData(), (new DataSet(hostY)).getData());

		 txtDelayData.setText(""); //clear the box
		 txtDelayData.setText("Avg Delay\t\tTime\n" + 
                                 "---------\t\t----"); 
		 for (i = 0; i < avg.length; i++) {
		    d = new Date(time[i]);
				txtDelayData.append("\n" + avg[i] + 
													"\t\t" + d.toString());
		 }
		 

     hostY2 = loss;
     //hostX2 = hostX;
     yx2 = new DataSet(false);
     yx2.setData(hostX);
     graphLoss.setValues(yx2.getData(), (new DataSet(hostY2)).getData());
     
     txtLossData.setText("Packets Lost\t\tTime\n" + 
                         "------------\t\t----"); 
     for (i = 0; i < loss.length; i ++)  {
		   d = new Date(time[i]);
    	 txtLossData.append("\n" + loss[i] + 
    		                  "\t\t" + d.toString());
		 }
     tpanel3.setEnabled(true);
     tpanel4.setEnabled(true);
		 lblCaption1.setText("Click on the graph to see the time and date");
		 lblCaption2.setText("Click on the graph to see the time and date");
		 this.time = time;
		 this.chartdata = null; //set chartdata = null since the graph isn't 
														//showing any data from this object
	}


	/** Displays a message box to the user
	 * @param msg - The message to display to the user
	 */
  public void displayErrMsg(String msg) {
		MsgDialog ed = new MsgDialog(thisFrame, "Error", msg, 
												"", true);
			ed.show();
			return;
	}


	public void addNotify()
	{
	    // Record the size of the window prior to calling parents addNotify.
	    Dimension d = getSize();

		super.addNotify();

		if (fComponentsAdjusted)
			return;

		// Adjust components according to the insets
		setSize(getInsets().left + getInsets().right + d.width, getInsets().top + getInsets().bottom + d.height);
		Component components[] = getComponents();
		for (int i = 0; i < components.length; i++)
		{
			Point p = components[i].getLocation();
			p.translate(getInsets().left, getInsets().top);
			components[i].setLocation(p);
		}
		fComponentsAdjusted = true;
	}

    // Used for addNotify check.
	boolean fComponentsAdjusted = false;

	//{{DECLARE_CONTROLS
	symantec.itools.awt.TabPanel tabPanel1;
	java.awt.Panel tpanel1;
	java.awt.Choice cmbGraphType;
	java.awt.Label label1;
	java.awt.Label lblCaption1;
	//java.awt.Panel graph;
	java.awt.Label label2;
	java.awt.Panel tpanel2;
	java.awt.TextArea txtDelayData;
	java.awt.Panel tpanel3;
	java.awt.Choice cmbGraphType2;
	java.awt.Label label3;
	java.awt.Label lblCaption2;
	//java.awt.Panel graphLoss;
	java.awt.Label label5;
	java.awt.Panel tpanel4;
	java.awt.TextArea txtLossData;
	java.awt.Button btnClose;
	//}}

	//{{DECLARE_MENUS
	//}}
	Frame thisFrame = this;
	Graph graph, graphLoss;
	

	 //TracertWrapper tw;
	 NetTest app;
	 String[] hostX = {};
   int hostY[] = {};
	 int dsIdx = 0;
   DataSet yx;
   DataSet mx;
   // repeat data sets for loss measures
   DataSet yx2;
   DataSet mx2;
   String[] hostX2 = {};
   int hostY2[] = {};
   int dsIdx2;
	 ChartData chartdata;
	 long time[];
	 private static final boolean debug = false;

	class SymWindow extends java.awt.event.WindowAdapter
	{
		public void windowClosing(java.awt.event.WindowEvent event)
		{
			Object object = event.getSource();
			if (object == DisplayGUI.this)
				Frame1_WindowClosing(event);
		}
	}

	 // Display name of host when user clicks inside a bar
   class GraphItemListener implements ItemListener {
      public void itemStateChanged(ItemEvent e) {
	 
	      if (chartdata != null && (time == null)) {
	        Point p = (Point) e.getItem();
	    
					debugPrint("p.x = " + p.x);
					debugPrint("chartdata.hostName[p.x] = " + chartdata.hostName[p.x]);
					MsgDialog d = new MsgDialog(thisFrame, "Host", chartdata.hostName[p.x],
													   chartdata.IPNum[p.x], true);
					d.show();
				}
				else {
					Point p = (Point) e.getItem();
	    
					debugPrint("p.x = " + p.x);
					Date d = new Date(time[p.x]);
					debugPrint("time[p.x] = " + time[p.x] + ", " + d.toString());
					MsgDialog md = new MsgDialog(thisFrame, "Time", 
																					d.toString(), true);
					md.show();
				}
					
					

      }
   }
   

	void Frame1_WindowClosing(java.awt.event.WindowEvent event)
	{
		setVisible(false);		 // hide the Frame
		System.exit(0);
	}

	class SymAction implements java.awt.event.ActionListener
	{
		public void actionPerformed(java.awt.event.ActionEvent event)
		{
		
			Object object = event.getSource();
            if (object == btnClose)
				btnClose_ActionPerformed(event);
		}
	}



	void btnTrace_ActionPerformed(java.awt.event.ActionEvent event)
	{
		//execute Tracert
		
    txtDelayData.setText("");
		txtLossData.setText("");

		app.executeTrace();

		
	}


	class SymItem implements java.awt.event.ItemListener
	{
		public void itemStateChanged(java.awt.event.ItemEvent event)
		{
			Object object = event.getSource();
			if (object == cmbGraphType)
				cmbGraphType_ItemStateChanged(event);
			else if (object == cmbGraphType2)
					    cmbGraphType2_ItemStateChanged(event);
		}
	}

	void cmbGraphType_ItemStateChanged(java.awt.event.ItemEvent event)
	{
		if ((cmbGraphType.getSelectedItem()).compareTo("Bar") == 0) 
			graph.setStyle(Graph.BAR);
		else if ((cmbGraphType.getSelectedItem()).compareTo("Line") == 0)
						graph.setStyle(Graph.LINE);
				 else graph.setStyle(Graph.PIE);
			 
	}

	void cmbGraphType2_ItemStateChanged(java.awt.event.ItemEvent event)
	{
		if ((cmbGraphType2.getSelectedItem()).compareTo("Bar") == 0) 
			graphLoss.setStyle(Graph.BAR);
		else if ((cmbGraphType2.getSelectedItem()).compareTo("Line") == 0)
						graphLoss.setStyle(Graph.LINE);
				 else graphLoss.setStyle(Graph.PIE);
			 
	}

	private void debugPrint(String s) {
       if (debug) System.out.println(s);
  }


	void btnThorough_ActionPerformed(java.awt.event.ActionEvent event)
	{
		app.executeThoroughTrace();
	}

	void menuItem1_ActionPerformed(java.awt.event.ActionEvent event)
	{
		// to do: code goes here.
			 
		//{{CONNECTION
		// Hide the Frame
		setVisible(false);
		//}}
	}

	void btnClose_ActionPerformed(java.awt.event.ActionEvent event)
	{
		// to do: code goes here.
			 
		//{{CONNECTION
		// Hide the Frame
		setVisible(false);
		//}}
	}
}
