package graph;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

import timing.Sample;

import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 * This class creates graphs and writes them to disk. It is passed some data, such
 * as titles for the graph, data samples, and the fileName to output, and it creates
 * a new graph, displaying it to the screen, and writing the graph to disk as a JPEG.
 * @author ben
 *
 */
public class Grapher extends ApplicationFrame {
   final int width = 1200;
   final int height = 750;

   /**
    * Create a new Grapher
    * @param applicationTitle Window title to display on graph (menu bar title)
    * @param chartTitle Title of the graph to desplay in the window
    * @param fileName Where to save graph
    * @param times Data samples to display
    */
   public Grapher( String applicationTitle , String chartTitle, String fileName, List<Sample> times) {
      super(applicationTitle);
      DefaultCategoryDataset dataset = new DefaultCategoryDataset();
	
      for (Sample s : times) {
    	 final int msb = msb(s.iters);
         dataset.addValue(s.setTime, "set-time",  String.format("2^%d",msb));
         dataset.addValue(s.listTime,  "list-time",  String.format("2^%d",msb));
      }
      JFreeChart lineChart = ChartFactory.createLineChart(
         chartTitle,
         "Iterations","Seconds",
         dataset,
         PlotOrientation.VERTICAL,
         true,true,false);
      File file = new File(fileName);
      try {
		ChartUtilities.saveChartAsJPEG(file, lineChart, width, height);
	} catch (IOException e) {
		e.printStackTrace();
	}
      
      ChartPanel chartPanel = new ChartPanel( lineChart );
      chartPanel.setPreferredSize( new java.awt.Dimension( 1000 , 600 ) );
      setContentPane( chartPanel );
   }

   /**
    * Take the log based 2 of an integer, rounding down to the nearest int.
    * @param n
    * @return
    */
   int msb(int n) {
      int msb = 0;
      while ((n >>= 1) != 0) ++msb;
      return msb;
   }
}