import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.io.*;
import java.net.*;

import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

public class Viewer extends ApplicationFrame implements ActionListener {
  String host;
  int port;
  DefaultCategoryDataset data,data2;

  public Viewer(String host, int port) {
    super("Clicker Viewer");
    this.host = host;
    this.port = port;
    this.data = new DefaultCategoryDataset();
    this.data2 = new DefaultCategoryDataset();

    JTabbedPane pane = new JTabbedPane();
    pane.addTab("Unique",createGraph(this.data));
    pane.addTab("Total",createGraph(this.data2));
    getContentPane().add(pane);
    getContentPane().add(createButtons(),BorderLayout.SOUTH);

    pack();
    show();
  }

  public Component createGraph(DefaultCategoryDataset dataset) {
    JFreeChart jfreechart = ChartFactory.createBarChart("Responses", "Answer", "Count", 
							dataset, PlotOrientation.VERTICAL, true, true, false);
    jfreechart.setBackgroundPaint(Color.white);
    CategoryPlot categoryplot = jfreechart.getCategoryPlot();
    categoryplot.setBackgroundPaint(Color.lightGray);
    categoryplot.setRangeGridlinePaint(Color.white);
    NumberAxis numberaxis = (NumberAxis)categoryplot.getRangeAxis();
    numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    CategoryAxis categoryaxis = categoryplot.getDomainAxis();
    categoryaxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(0.52D));
    BarRenderer renderer = (BarRenderer)categoryplot.getRenderer();
    ChartPanel chartpanel = new ChartPanel(jfreechart);
    chartpanel.setPreferredSize(new Dimension(500, 270));    
    return chartpanel;
  }

  public Component createButtons() {
    JPanel panel = new JPanel();

    JButton butt = new JButton("Results");
    butt.addActionListener(this);
    panel.add(butt);

    butt = new JButton("New");
    butt.addActionListener(this);
    panel.add(butt);

    butt = new JButton("Next");
    butt.addActionListener(this);
    panel.add(butt);

    butt = new JButton("Prev");
    butt.addActionListener(this);
    panel.add(butt);

    butt = new JButton("Shutdown");
    butt.addActionListener(this);
    panel.add(butt);

    return panel;
  }

  public void actionPerformed(ActionEvent event) {
    String cmd=event.getActionCommand();
    if (cmd.equals("Results")) {
      getResults();
    } else {
      sendSimple(cmd.toLowerCase());
      if ("Prev".equals(cmd) || "Next".equals(cmd))
	getResults();
    }
  }

  public void sendSimple(String cmd) {
    try {
      Socket s = new Socket(this.host, 8888);
      PrintWriter pw = new PrintWriter(s.getOutputStream());
      pw.println(cmd);
      pw.flush();
      pw.close();
      s.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void getResults() {
    try {
      Socket s = new Socket(this.host, 8888);
      PrintWriter pw = new PrintWriter(s.getOutputStream());
      pw.println("results");
      pw.flush();
      BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
      int count = Integer.parseInt(br.readLine());
      String uni = "Unique", tot = "Total";
      this.data.clear();
      this.data2.clear();
      String cat = br.readLine();
      while (cat != null) {
	System.out.println(cat);
	this.data.addValue(Double.parseDouble(br.readLine()),uni,cat);
	this.data2.addValue(Double.parseDouble(br.readLine()),tot,cat);
	
	cat = br.readLine();
      }
      pw.close();
      s.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void main(String args[]) {
    final String host;
    if (args.length > 0)
      host = args[0];
    else
      host = "pieces.jerrod.net";

    final int port;
    if (args.length > 1)
      port = Integer.parseInt(args[1]);
    else
      port = 8888;

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
	public void run() {
	  new Viewer(host,port);
	}
      });
  }
}
