//package ptolemy.plot;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;

import javax.swing.JPanel;
import java.util.*;
import java.net.URL;

import ptolemy.plot.*;

import java.util.StringTokenizer;
import java.util.NoSuchElementException;

import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.KeyStroke;
//import javax.swing.ImageIcon;


public class PlotPanel extends JPanel implements ActionListener, ItemListener{
    private static boolean DEBUG = true;
    private boolean flag = false;
    private Plot plot;

    private String temp;
    private Vector vec;
    private RunCgi infile;

    private String token;
    private ConfigFile conf;
    private int num_vals;
    private double x_max, x_min;
    private double[] x_vals, y_vals;

    private JMenuItem menuItem;
    private JPopupMenu popup;
    //private PopupActionListener actionListener;
    String newline = "\n";

   
    public PlotPanel() {
	
	if (DEBUG) System.err.println("constructor for PlotPanel");
        plot = new Plot();
	add(plot);
	conf = new ConfigFile();
    }

    public PlotPanel(DataStruct datastruct) {
	if (DEBUG) System.err.println("DataStruct constructor for PlotPanel");
        plot = new Plot();
	add(plot);
	conf = new ConfigFile();
	// add popup menu
	popup = new JPopupMenu();

        //for (int i=1;i<vec.size(); i++) {
            //temp=vec.elementAt(i).toString();

            // Add image icon to JButton in the future //

            menuItem = new JMenuItem("Add Dataset");
            menuItem.addActionListener(this);
            popup.add(menuItem);

            menuItem = new JMenuItem("Remove Dataset");
            menuItem.addActionListener(this);
            popup.add(menuItem);

	    // Add listener to components that can bring up popup menus
	    MouseListener popupListener = new PopupListener();
	    plot.addMouseListener(popupListener);
	    
        //}
	plot.add(popup);

	// read data points
	if (DEBUG) System.err.println("datastruct.range_x="+datastruct.range_x);
	if (DEBUG) System.err.println("file url="+conf.getURL(datastruct.filename));
	StringTokenizer parser = new StringTokenizer(datastruct.range_x, " ",true);
	try {
	    while (parser.hasMoreTokens()) {
		token = parser.nextToken();
		if (!token.equals(" ")) {
		    if (!flag) {
			flag=true;
			x_min=(double) new Double(token).doubleValue();
		    	if (DEBUG) System.err.println("x_min="+x_min);
		    }
		    else {
			x_max=(double) new Double(token).doubleValue();
		    	if (DEBUG) System.err.println("x_max="+x_max);
		    }
		}
	    }
	} catch (NoSuchElementException e) {
                e.printStackTrace();
        }

	num_vals=createArr(conf.getURL(datastruct.filename)); 
	if (DEBUG) System.err.println("num_vals="+num_vals);
        plot.setTitle(datastruct.title);
        plot.setXRange(x_min, x_max);
        plot.setMarksStyle("none");
        //plot.addLegend(0, "ideal");

        //boolean first = true;

	// j = dataset number
        //plot.addPoint(j, 0.0, 0.0, false);
        //for (int i = 0; i <= 400; i++) {
        //plot.addPoint(j, (double)i, approximation, first);

        plot.addPoint(0, x_vals[0], y_vals[0], false);
        for (int i = 1; i <= num_vals; i++) {
            plot.addPoint(0, x_vals[i], y_vals[i], true);
	}


    }

    public void readData(String url) {
        //if (DEBUG) System.err.println("PlotPanel readData - ");
        infile = new RunCgi();
        infile.ReadIt(url);
        vec = infile.file;
    }

    public int createArr (String url) {
	// read data
	readData(url);
	if (DEBUG) System.err.println("read data");
	if (DEBUG) System.err.println("vec size "+vec.size());
	num_vals=0;
	x_vals = new double[vec.size()-11];
	y_vals = new double[vec.size()-11];
	// parse x y vals
	flag=false;
        for (int i=11;i<vec.size();i++) {
            temp=vec.elementAt(i).toString();
	    //if (DEBUG) System.err.println("temp="+temp);
            temp.trim();

            StringTokenizer parser = new StringTokenizer(temp, " ",true);
            try {
		while (parser.hasMoreTokens()) {
		    token = parser.nextToken();
		    if (!token.equals(" ")) {
			if (!flag) {
			    flag=true;
			    x_vals[num_vals]=(double) new Double(token).doubleValue();
			    //if (DEBUG) System.err.println("x_vals="+x_vals[num_vals]);
			}
			else {
			    flag=false;
			    //if (DEBUG) System.err.println("token="+token);
			    y_vals[num_vals]=(double) new Double(token).doubleValue();
			    //if (DEBUG) System.err.println("y_vals="+y_vals[num_vals]);
			    num_vals++;
			}
		    }
            }
            } catch (NoSuchElementException e) {
                e.printStackTrace();
            }
	}
	num_vals--;
	return(num_vals);
    }

    public void update(Vector list) {

	Integer Inum = (Integer)list.elementAt(0);
	int num = Inum.intValue();
	System.err.println("num="+num);

        plot.setTitle("Fourier Series Approximation to a Square Wave");
        plot.setXRange(0, 400);
        plot.setMarksStyle("none");
        plot.addLegend(0, "ideal");
        plot.addLegend(1, "1 sinusoid");
        for (int j = 2; j <= 4; j++) {
            plot.addLegend(j, j + " sinusoids");
        }

        boolean first = true;
        plot.addPoint(0, 0.0, 0.0, false);
        for (int i = 0; i <= 400; i++) {
            if (i <= 200) {
                plot.addPoint(0, (double)i, 1.0, true);
            }
            if (i >= 200) {
                plot.addPoint(0, (double)i, -1.0, true);
            }
        }
        plot.addPoint(0, 400.0, 0.0, true);
    }

class PopupListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
        maybeShowPopup(e);
    }

    public void mouseReleased(MouseEvent e) {
        maybeShowPopup(e);
    }

    private void maybeShowPopup(MouseEvent e) {
        if (e.isPopupTrigger()) {
            popup.show(e.getComponent(),
                       e.getX(), e.getY());
        }
    }
}


    public void actionPerformed(ActionEvent e) {
        JMenuItem source = (JMenuItem)(e.getSource());
        String s = "Action event detected."
                   + newline
                   + "    Event source: " + source.getText()
                   + " (an instance of " + getClassName(source) + ")";
        if (DEBUG) System.err.println("actionPerformed: "+s + newline);
    }

    public void itemStateChanged(ItemEvent e) {
        JMenuItem source = (JMenuItem)(e.getSource());
        String s = "Item event detected."
                   + newline
                   + "    Event source: " + source.getText()
                   + " (an instance of " + getClassName(source) + ")"
                   + newline
                   + "    New state: " 
                   + ((e.getStateChange() == ItemEvent.SELECTED) ?
                     "selected":"unselected");
        if (DEBUG) System.err.println("itemStateChanged: "+s + newline);
    }

    // Returns just the class name -- no package info.
    protected String getClassName(Object o) {
        String classString = o.getClass().getName();
        int dotIndex = classString.lastIndexOf(".");
        return classString.substring(dotIndex+1);
    }

}

