import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;

import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.RegularTimePeriod;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;

/**
 * 
 * @author Felipe Lopez P. - Cristian Carrasco G.
 * Class grafico: Esta clase implementa los graficos X vs T, Y vs T y Y vs X
 */
public class grafico extends ApplicationFrame implements ActionListener{
	/** Tiempo de graficado */
	private double timeWindowSize;
    
	/** The number of subplots. */
    public static final int SUBPLOT_COUNT = 3;
    
    /** The datasets. */
    private XYSeriesCollection[] datasets;
    
    /** The most recent value added to series 1. */
    private double[] lastValue = new double[SUBPLOT_COUNT];


/**
 * Constructor de clase grafico
 * @param title Titulo del grafico
 * @param fondo Jpanel donde el insertado el grafico
 * @param timeWindowSize Tiempo de graficado
 */
    public grafico(final String title, JPanel fondo, double timeWindowSize) {
    	  super(title);
          this.timeWindowSize=timeWindowSize;
          final CombinedDomainXYPlot plot1 = new CombinedDomainXYPlot(new NumberAxis("Time"));
          final CombinedDomainXYPlot plot2 = new CombinedDomainXYPlot(new NumberAxis("Time"));
          this.datasets = new XYSeriesCollection[SUBPLOT_COUNT];
          final XYSeries series1 = new XYSeries("Mass");
          final XYSeries series2 = new XYSeries("Mass");
          final XYSeries series3 = new XYSeries("Mass",false);
          this.datasets[0] = new XYSeriesCollection(series1);
          this.datasets[1] = new XYSeriesCollection(series2);
          this.datasets[2] = new XYSeriesCollection(series3);
          String eje = "X";
          for (int i = 0; i < SUBPLOT_COUNT-1; i++) {
              this.lastValue[i] = 100.0;
              if(i==1)eje = "Y";
              final NumberAxis rangeAxis = new NumberAxis(eje);
              rangeAxis.setAutoRangeIncludesZero(false);
              final XYPlot subplot = new XYPlot(
                      this.datasets[i], null, rangeAxis, new StandardXYItemRenderer()
              );
              subplot.setBackgroundPaint(Color.lightGray);
              subplot.setDomainGridlinePaint(Color.white);
              subplot.setRangeGridlinePaint(Color.white);
              subplot.getRenderer().setSeriesPaint(0, Color.BLUE);
              if(i==0)plot1.add(subplot);
              else plot2.add(subplot);
          }               
              
          final JFreeChart chart1 = new JFreeChart("Grafico X vs tiempo", plot1);
          chart1.setBorderPaint(Color.black);
          chart1.setBorderVisible(true);
          chart1.setBackgroundPaint(Color.white);
          
          plot1.setBackgroundPaint(Color.lightGray);
          plot1.setDomainGridlinePaint(Color.white);
          plot1.setRangeGridlinePaint(Color.white);
          //plot1.getRenderer().setSeriesPaint(0, Color.BLUE);
          final ValueAxis axis = plot1.getDomainAxis();
          axis.setAutoRange(true);
          axis.setFixedAutoRange(timeWindowSize);  // 30 seconds

          final JFreeChart chart2 = new JFreeChart("Grafico Y vs tiempo", plot2);
          chart2.setBorderPaint(Color.black);
          chart2.setBorderVisible(true);
          chart2.setBackgroundPaint(Color.white);
          
          plot2.setBackgroundPaint(Color.lightGray);
          plot2.setDomainGridlinePaint(Color.white);
          plot2.setRangeGridlinePaint(Color.white);
          //plot2.getRenderer().setSeriesPaint(0, Color.BLUE);
          final ValueAxis axis2 = plot2.getDomainAxis();
          axis2.setAutoRange(true);
          axis2.setFixedAutoRange(timeWindowSize);  // 30 seconds
        
          JFreeChart chart3 = ChartFactory.createXYLineChart("Grafico Y v/s X",
          	      "X", // Leyenda Eje X
          	      "Y", // Leyenda Eje Y
          	      this.datasets[2],
          	      PlotOrientation.VERTICAL,
          	      false,
          	      false,
          	      false
          	      );
	XYPlot plot3 = chart3.getXYPlot();
	chart3.setBorderPaint(Color.black);
    chart3.setBorderVisible(true);
    plot3.getRenderer().setSeriesPaint(0, Color.BLUE);
    
        final ValueAxis axis3 = plot3.getDomainAxis();
        axis3.setAutoRange(true);
        final ValueAxis ayis3 = plot3.getRangeAxis();
        ayis3.setInverted(true);          

          final ChartPanel chartPanel1 = new ChartPanel(chart1);
          final ChartPanel chartPanel2 = new ChartPanel(chart2);
          final ChartPanel chartPanel3 = new ChartPanel(chart3);

          fondo.setLayout(new BoxLayout(fondo, BoxLayout.PAGE_AXIS));

          fondo.add(chartPanel2);
          fondo.add(chartPanel1);
          fondo.add(chartPanel3);
                  
          chartPanel1.setPreferredSize(new java.awt.Dimension(500, 190)); //500,380
          chartPanel1.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
          chartPanel2.setPreferredSize(new java.awt.Dimension(500, 190));//500,270
          chartPanel2.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));   
          chartPanel3.setPreferredSize(new java.awt.Dimension(500, 190));
          chartPanel3.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); 
                   
          JButton button = new JButton("Clear Plots");
          button.addActionListener(this);
          fondo.add(button);
          setContentPane(fondo);
          
      }
      
    /**
     * Metodo que añade nuevos puntos para graficar
     * @param x Posicion x de la masa
     * @param y Posicion y de la masa
     * @param t Tiempo del dato
     * @param samplingt Tiempo sampling del simulador
     */
      public void add(double x, double y, float t, float samplingt){
    	  if(this.datasets[2].getSeries(0).getItemCount()>=(int)(timeWindowSize/samplingt))//30 seg/sampletime(0.08)
    	  this.datasets[2].getSeries(0).remove(0);	
      this.datasets[0].getSeries(0).add((double)t,x);	
      this.datasets[1].getSeries(0).add((double)t,y);
      this.datasets[2].getSeries(0).add(x,y); 	
      }
      
      /**
       * Acciones que se ejecutan cuando se desea borrar los graficos 
       */
      public void actionPerformed(final ActionEvent e) { 
    	  this.datasets[0].getSeries(0).delete(0,this.datasets[2].getSeries(0).getItemCount()-1);
    	  this.datasets[1].getSeries(0).delete(0,this.datasets[2].getSeries(0).getItemCount()-1);
    	  this.datasets[2].getSeries(0).delete(0,this.datasets[2].getSeries(0).getItemCount()-1);
          
      }
      
      
      }
