package View;

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.Map;
import java.util.Set;

import javax.swing.JCheckBox;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import Controller.Controller;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYStepRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 * Displays the number of already learned word in each iteration in a graph.
 * @author simon
 *
 */

public class WordsLearnedOverTime extends DataPanel {

	ChartPanel chartPanel; 
	JCheckBox restrict;
	
	public WordsLearnedOverTime(Controller controller) {
		super(controller);
		
        this.setLayout(new GridBagLayout());
        GridBagConstraints c= new GridBagConstraints();
        c.gridx=0;
        c.gridy=0;
        c.weightx = 1.0;
        c.weighty = 0.1;
        restrict= new JCheckBox("restrict to CurrentIteration");
        ChangeListener changeListener = new ChangeListener() {
        	public void stateChanged(ChangeEvent changeEvent) {
        		GUI.updatePanels();
            }
        };
        restrict.addChangeListener(changeListener);
        this.add(restrict,c);
        
        XYDataset dataset = createFullDataset();
        JFreeChart chart = createChart(dataset);
        chartPanel = new ChartPanel(chart);
        c.gridy=1;
        c.weighty = 0.9;
        c.fill = GridBagConstraints.BOTH;
        this.add(chartPanel,c);
		
	}
	
	/**
	 * This method is called every time the iteration changes and produces a new chart.
	 * The new chart is almost the same but has the marker for the current iteration at a different position. The dataset stays the same.
	 */
	public void updatePanel(){
		XYDataset dataset;
		if(restrict.isSelected()){
			dataset = createRestrictedDataset();
		}else{
			dataset = createFullDataset();
		}
        JFreeChart chart = createChart(dataset);
        chartPanel.setChart(chart);
	}

	/**
	 * This method creates the data set which consists of the amount of words learned for all the iterations.
	 * @return
	 */
    private XYDataset createFullDataset() {
        
    	final XYSeries series1 = new XYSeries("WordsLearnedOverTime");
    	
    	Map<Integer,Integer> map=cont.getWordsLearnedOverTimeData();
    	for(Map.Entry<Integer,Integer> entry : map.entrySet()){
    		series1.add(entry.getKey(),entry.getValue());
    	}

        final XYSeriesCollection dataset = new XYSeriesCollection();
        dataset.addSeries(series1);
        
        return dataset;
        
    }
    
    /**
	 * This method creates the data set which consists of the amount of words learned for all the iterations.
	 * @return
	 */
    private XYDataset createRestrictedDataset() {
       
    	final XYSeries series = new XYSeries("WordsLearnedOverTime");
   	
    	Map<Integer,Integer> map=cont.getWordsLearnedOverTimeData();
   		for(Map.Entry<Integer,Integer> entry : map.entrySet()){
   			if(entry.getKey()<=cont.getCurrentIteration()){
   				series.add(entry.getKey(),entry.getValue());
   			}
   		}

   		final XYSeriesCollection dataset = new XYSeriesCollection();
   		dataset.addSeries(series);
       
   		return dataset;
       
   }

    /**
     * Creates the chart for the given dataset
     * @param dataset
     * @return
     */
    
    private JFreeChart createChart(final XYDataset dataset) {
        
        // create the chart
        final JFreeChart chart = ChartFactory.createXYLineChart(
            "WordsLearnedOverTime",      // chart title
            "iteration",                      // x axis label
            "learned words #",                      // y axis label
            dataset,                  // data
            PlotOrientation.VERTICAL,
            true,                     // include legend
            true,                     // tooltips
            false                     // urls
        );

        chart.setBackgroundPaint(Color.white);
        
        final XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setDomainGridlinePaint(Color.lightGray);
        plot.setRangeGridlinePaint(Color.lightGray);
        
        
        final XYLineAndShapeRenderer renderer = new XYStepRenderer();
        renderer.setSeriesLinesVisible(0, true);
        renderer.setSeriesShapesVisible(0, true);
        plot.setRenderer(renderer);
        
        // add the marker for the current iteration
        int iter=cont.getCurrentIteration();
        ValueMarker marker = new ValueMarker(iter);
        marker.setLabel("currentIteration");
        plot.addDomainMarker(marker);
        
        // change the auto tick unit selection to integer
        final NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
        domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
                
        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        
        if(restrict.isSelected()){
        	rangeAxis.setRange(0,cont.getNumberOfAppearedWords(cont.getCurrentIteration()));
        }else{
        	rangeAxis.setRange(0,cont.getWordTableData().size());
        }
        
        return chart;
        
    }
    
}
