package com.scottlangley.elect98;
/*Copyright 1998 by Scott Langley.
All rights reserved.
*/
import java.net.*;
import java.io.*;
import java.awt.*;
import java.applet.*;

final public class Elect98 extends Applet {
    URL url;
    URLConnection urlConnection;

    int contentLength=0, total_bytes_read = 0, responseCode = 0;
    BufferedInputStream in = null;

//    java.io.FileInputStream in;

    Label title = new Label("1998 Congressional Elections Predictor and 106th Congress Simulation",Label.CENTER);
    Label blank1 = new Label(" ");
    Label blank2 = new Label(" ");
    Label blank3 = new Label(" ");
    Label blank4 = new Label(" ");
    Label blank5 = new Label(" ");
    SliderPanel sliderPanel = new SliderPanel();
    CongressDisplay c105 = new CongressDisplay("105th Congress");
    CongressDisplay c106 = new CongressDisplay("106th Congress");
    Button b1 = new Button("Calculate Prediction");
//    Button b2 = new Button("Simulate Results");
    Button b2 = new Button("View Prediction in Detail");
    Button b3 = new Button("About");
    Congress predictedCongress;
    CardLayout cl = new CardLayout();
    Panel cards = new Panel();
    Panel first = new Panel();
    Panel second = new Panel();
    Panel header = new Panel();
    Panel buttons = new Panel();
    TextArea resultsText = new TextArea(10,61);
    short[] parameters;
  public void init() {
		super.init();
    GridBagLayout gbl = new GridBagLayout();
    FlowLayout fl = new FlowLayout();
    BorderLayout bl = new BorderLayout();
    setLayout(bl);
    this.setBackground(Color.blue);
		addNotify();
    title.setForeground(Color.white);
//    title.setForeground(Color.red);
    title.setFont(new Font("DIALOG",Font.BOLD,14));
    b1.setBackground(Color.red);
    b2.setBackground(Color.red);
    b3.setBackground(Color.red);

    buttons.setLayout(fl);
//    p.add(title);
    buttons.add(b1);
    buttons.add(b2);
    buttons.add(b3);

    header.setLayout(new BorderLayout());

    header.add("North",title);
    header.add("Center",blank5);
    header.add("South",buttons);
    this.add("North",header);
    cards.setLayout(cl);
    cl.setHgap(20);
    cl.setVgap(10);

    first.setLayout(gbl);




//    SliderPanel.add(first, title, 0,0,19,1,0.0,0.0,GridBagConstraints.NONE, GridBagConstraints.CENTER);
   // SliderPanel.add(first, blank1, 0,0,8,1,10.0,10.0,GridBagConstraints.NONE, GridBagConstraints.CENTER);
   // SliderPanel.add(first, blank2, 0,1,1,9,0.0,0.0,GridBagConstraints.NONE, GridBagConstraints.CENTER);
    SliderPanel.add(first, sliderPanel, 0,0,6,10,0.0,0.0,GridBagConstraints.NONE, GridBagConstraints.CENTER);
    SliderPanel.add(first, blank1,6,0,1,10,0.0,0.0,GridBagConstraints.NONE, GridBagConstraints.CENTER);
//    SliderPanel.add(this, b1, 12,3,5,1,0.0,0.0,GridBagConstraints.CENTER, GridBagConstraints.CENTER);
//    SliderPanel.add(this, b2, 17,3,3,1,0.0,0.0,GridBagConstraints.CENTER, GridBagConstraints.CENTER);


    c105.setValues((short)206, (short)228, (short)45, (short)55);
    c106.resetValues();

    SliderPanel.add(first, c105, 7,0,6,4,10.0,10.0,GridBagConstraints.NONE, GridBagConstraints.CENTER);
    SliderPanel.add(first, c106, 7,6,6,4,10.0,10.0,GridBagConstraints.NONE, GridBagConstraints.CENTER);
//    SliderPanel.add(first, blank4, 1,7,1,6,10.0,10.0,GridBagConstraints.NONE, GridBagConstraints.CENTER);

		resize(550,450);
    cards.add("first",first);
//    second.add(resultsText);
    cards.add("second",second);
    resultsText.setBackground(Color.white);
    resultsText.setEditable(false);
    //cards.add("second",c105);
    //cards.add("second",c106);
    this.add("Center",cards);


    //Parameters parameters;
  try{
      in = new BufferedInputStream(getConnection("http://www.scottlangley.com/congress/elections98/e98.dat"));
//    in = new java.io.FileInputStream("g:\\Congress\\e98.dat");
    java.io.DataInputStream dataIn = new java.io.DataInputStream(in);
    predictedCongress = new Congress(dataIn);
//    short[] parameters = new Parameters(20,30,42,25);
//    predictedCongress.elect(parameters);

  }
/*  catch (MalformedURLException e) {
        	//Throw "Can't do this URL"
  }
*/  
  catch (IOException e){
    e.printStackTrace();
  }
  finally {try {if (in !=null) in.close();}catch(IOException e){}}
  }
    InputStream getConnection(String webAddress) throws MalformedURLException, IOException, FileNotFoundException{
			//Is my web address formulated correctly?
	    	url = new URL(webAddress);
            //Create a connection object
        	urlConnection = url.openConnection();
            //Now, adjust setup parameters for the connection
            urlConnection.setUseCaches(false);
            //set general http request properties
            //initiate connection
            urlConnection.connect();
            contentLength = urlConnection.getContentLength();
            /*if(urlConnection instanceof HttpURLConnection) {
            	httpConnection = (HttpURLConnection) urlConnection;
                responseCode = httpConnection.getResponseCode();
	            if(responseCode>=400) {
      	            System.out.println(httpConnection.getResponseMessage());
                    throw new FileNotFoundException();
                }
            }*/
            return urlConnection.getInputStream();
    }
  public Elect98() {
  }
  public boolean action(Event event, Object object) {
    if (event.target == b1){
//      predictedCongress.elect(sliderPanel.getParameters(),false);
      cl.first(cards);
      parameters = sliderPanel.getParameters();
      predictedCongress.elect(parameters);

//      predictedCongress.electDetailed(sliderPanel.getParameters());
      c106.newValues((short)206, (short)228, (short)45, (short)55,predictedCongress.getHouseDemocrats(), predictedCongress.getHouseRepublicans(), predictedCongress.getSenateDemocrats(), predictedCongress.getSenateRepublicans());
    }
    else if (event.target == b2){


//        cl.invalidateLayout(cards);


//        resultsText.setText("Process...");
//        ((CardLayout)cards.getLayout()).show(cards,"second");
//        invalidate();
        //resize(preferredSize());
        //validate();
        //second.validate();
        //validate();
        if(parameters != null){
          cl.first(cards);
          cl.next(cards);
          invalidate();
          validate();
          predictedCongress.electDetailed(parameters, resultsText);
          second.add(resultsText);
          second.validate();
        }
//        cl.first(cards);
//        cl.next(cards);

    }
    else if (event.target == b3){
      try{
        getAppletContext().showDocument(new URL("http://www.scottlangley.com/congress/elections98/about.html"));
      }
      catch(MalformedURLException e){
      }
    }

    else
      return  super.action(event, object);
    return(true);
  }

}
class SliderPanel extends Panel{
    Label instruction = new Label("Adjust Relative to the Last Election");
    LabeledSlider incumbentSlider = new LabeledSlider("Change in the Advantage of Incumbency","Challengers","Incumbents",-100,100,0);
    LabeledSlider partySlider = new LabeledSlider("Change in Party Support","Democrats","Republicans",-100,100,0);
    Label instruction2 = new Label("Adjust These Parameters if Desired");
    LabeledSlider openSeatSlider = new LabeledSlider("Gain/Loss Due to Open Seat","Other Pary","Vacating Party",-100,100,-42);
    LabeledSlider freshmanSlider = new LabeledSlider("Incumbency Gain for Freshmen","Challenger","Freshman Incumbent",-100,100,20);
  SliderPanel(){
    Panel sliderPanel = new Panel();
    GridBagLayout gbl = new GridBagLayout();
    setLayout(gbl);
    this.setBackground(Color.white);
    this.setFont(new Font("DIALOG",Font.ITALIC,12));
    instruction.setForeground(Color.red);

    SliderPanel.add(this, instruction, 0,1,1,1,0.0,0.0,GridBagConstraints.CENTER, GridBagConstraints.NORTH);
    //sliderPanel.add(instruction);

    SliderPanel.add(this, incumbentSlider, 0,2,1,1,0.0,0.0,GridBagConstraints.CENTER, GridBagConstraints.CENTER);
    //sliderPanel.add(incumbentSlider);

    SliderPanel.add(this, partySlider, 0,3,1,1,0.0,0.0,GridBagConstraints.CENTER, GridBagConstraints.CENTER);
    //sliderPanel.add(partySlider);
    instruction2.setForeground(Color.red);
    SliderPanel.add(this, instruction2, 0,4,1,1,0.0,0.0,GridBagConstraints.CENTER, GridBagConstraints.CENTER);
    //sliderPanel.add(instruction2);

    SliderPanel.add(this, openSeatSlider, 0,5,1,1,0.0,0.0,GridBagConstraints.CENTER, GridBagConstraints.CENTER);
    //sliderPanel.add(openSeatSlider);

    SliderPanel.add(this, freshmanSlider, 0,6,1,1,0.0,0.0,GridBagConstraints.CENTER, GridBagConstraints.CENTER);
    //sliderPanel.add(freshmanSlider);

  }
//  Parameters getParameters(){
  short[] getParameters(){
    return new short[] {(short)partySlider.getValue(), (short)incumbentSlider.getValue(), (short)(-1*openSeatSlider.getValue()), (short)freshmanSlider.getValue()};
    //return new Parameters(partySlider.getValue(), incumbentSlider.getValue(), (short)(-1*openSeatSlider.getValue()), freshmanSlider.getValue());
  }
  static void add(Container cont, Object arg, int x, int y, int w, int h,
    double weightx, double weighty){
    add(cont, arg, x, y, w, h, weightx, weighty, GridBagConstraints.BOTH, GridBagConstraints.CENTER);
  }
  static void add(Container cont, Object arg, int x, int y, int w, int h,
    double weightx, double weighty, int fill, int anchor){
    GridBagLayout gbl = (GridBagLayout) cont.getLayout();
    GridBagConstraints gbc = new GridBagConstraints();
    Component comp;
    gbc.anchor = anchor;
    gbc.fill = fill;
    gbc.gridx = x;
    gbc.gridy = y;
    gbc.gridwidth = w;
    gbc.gridheight = h;
    gbc.weightx = weightx;
    gbc.weighty = weighty;
    comp = (Component)arg;
    cont.add(comp);
    gbl.setConstraints(comp, gbc);
  }

}

class CongressDisplay extends Panel {
  Label heading;
  Label hD = new Label("  ?"  +"   ");
  Label sD = new Label("  ?"+"   ");
  Label hR = new Label("  ?" +"   ");
  Label sR = new Label("  ?"  +"   ");
  Label hI = new Label("  ?" +"   ");
  Label sI = new Label("  ?"  +"   ");
  public CongressDisplay(String heading){
    GridBagLayout gbl = new GridBagLayout();
    setLayout(gbl);
    this.setBackground(Color.white);
    this.setFont(new Font("DIALOG",Font.PLAIN,10));
    Label headLabel = new Label(heading);
    headLabel.setFont(new Font("DIALOG",Font.BOLD,12));

    SliderPanel.add(this, headLabel, 0,0,3,2,0.0,0.0,GridBagConstraints.CENTER, GridBagConstraints.CENTER);
    SliderPanel.add(this, new Label("House"), 1,2,1,2,0.0,0.0,GridBagConstraints.CENTER, GridBagConstraints.EAST);
    SliderPanel.add(this, new Label("Senate"), 2,2,1,2,0.0,0.0,GridBagConstraints.CENTER, GridBagConstraints.EAST);
    SliderPanel.add(this, new Label("  Democrats"), 0,4,1,2,0.0,0.0);
    SliderPanel.add(this, hD, 1,4,1,2,0.0,0.0,GridBagConstraints.BOTH,GridBagConstraints.CENTER);
    SliderPanel.add(this, sD, 2,4,1,2,0.0,0.0,GridBagConstraints.BOTH,GridBagConstraints.CENTER);
    SliderPanel.add(this, new Label("  Republicans"), 0,6,1,2,0.0,0.0);
    SliderPanel.add(this, hR, 1,6,1,2,0.0,0.0,GridBagConstraints.BOTH,GridBagConstraints.CENTER);
    SliderPanel.add(this, sR, 2,6,1,2,0.0,0.0,GridBagConstraints.BOTH,GridBagConstraints.CENTER);
    SliderPanel.add(this, new Label("  Independents"), 0,8,1,2,0.0,0.0);
    SliderPanel.add(this, hI, 1,8,1,2,0.0,10.0,GridBagConstraints.BOTH,GridBagConstraints.EAST);
    SliderPanel.add(this, sI, 2,8,1,2,0.0,10.0,GridBagConstraints.BOTH,GridBagConstraints.EAST);
    SliderPanel.add(this, new Label(" "), 0,9,1,1,0.0,0.0);
    this.show();

  }
  void setValues(short hD, short hR, short sD, short sR){
    this.hD.setText("  "+hD+"   ");
    this.hR.setText("  "+hR+"   ");
    this.sD.setText("    "+sD+"   ");
    this.sR.setText("    "+sR+"   ");
    this.hI.setText("      1");
    this.sI.setText("      0");
  }
  void newValues(short ohD, short ohR, short osD, short osR, short nhD, short nhR, short nsD, short nsR ){
    this.hD.setText(nhD+gain(nhD-ohD));;
    this.hR.setText(nhR+gain(nhR-ohR));
    this.sD.setText("    "+nsD+gain(nsD-osD));
    this.sR.setText("    "+nsR+gain(nsR-osR));
    this.hI.setText("    1");
    this.sI.setText("      0");
  }
  void resetValues(){
    this.hD.setText("?   ");
    this.hR.setText("?   ");
    this.sD.setText("?   ");
    this.sR.setText("?   ");
    this.hI.setText("?   ");
    this.sI.setText("?   ");
  }
  static String gain(int difference){

    if(difference == 0)
      return "    ";
    else{
      StringBuffer temp = new StringBuffer();
      temp.append('(');
      if(difference>0)
        temp.append('+');
      else
        temp.append(' ');
      temp.append(difference);
      temp.append(')');
      return temp.toString();
    }
  }

}
/*class Util{
  static void add(Container cont, Object arg, int x, int y, int w, int h,
    double weightx, double weighty){
    add(cont, arg, x, y, w, h, weightx, weighty, GridBagConstraints.BOTH, GridBagConstraints.CENTER);
  }
  static void add(Container cont, Object arg, int x, int y, int w, int h,
    double weightx, double weighty, int fill, int anchor){
    GridBagLayout gbl = (GridBagLayout) cont.getLayout();
    GridBagConstraints gbc = new GridBagConstraints();
    Component comp;
    gbc.anchor = anchor;
    gbc.fill = fill;
    gbc.gridx = x;
    gbc.gridy = y;
    gbc.gridwidth = w;
    gbc.gridheight = h;
    gbc.weightx = weightx;
    gbc.weighty = weighty;
    comp = (Component)arg;
    cont.add(comp);
    gbl.setConstraints(comp, gbc);
  }
}    */

