package View;

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

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;

import Controller.Controller;
import Model.Meaning;
import Model.Word;

/**
 * The Graph where the development of the Comprehension Score for the focused words are displayed.
 * 
 * @author simon
 *
 */

public class WordComprehensionScore extends DataPanel {

	
	public WordComprehensionScore(Controller controller) {
		super(controller);
		
	}

	/**
	 * This method is called every time the iteration changed or a word is added to the focused table.
	 * It draws a whole new graph.
	 */
	
	public void updatePanel(){
		this.removeAll();
		Set<Word> words=cont.getFocusedWords();
		
		this.setLayout(new GridLayout(1,1));
		
		
		//print the graphs
		XYDataset data=createDataset(words);
		if(data!=null){
			JFreeChart chart=createChart(data);
			ChartPanel chartPanel = new ChartPanel(chart);
			this.add(chartPanel);
		}
		
	}
	
	/**
	 * Creates the dataset with all the comprehension scores for each iteration for all the words in the set. 
	 * @param words The set of words for which the Comprehesion score should be displayed.
	 * @return a Dataset suitable to be displayed by JFreeChart
	 */
    private XYDataset createDataset(Set<Word> words) {
        
    	final XYSeriesCollection dataset = new XYSeriesCollection();
    	
    	//iteate over all the words in the set
    	Iterator<Word> it = words.iterator();
		while (it.hasNext()){
			Word word=it.next();
			String name=word.getStringRep();
			final XYSeries series = new XYSeries(name);
    	
			series.add(0,0);
			//iterate over all the iterations the word occured in. 
			int lastIt=0;
			double lastProb=0.0;
			Map<Integer, Double> map;
			try {
				map = cont.getComprehensionScore(word);
				for(Map.Entry<Integer,Double> entry : map.entrySet()){
					series.add(entry.getKey(),entry.getValue());
					if(entry.getKey()> lastIt){
						lastIt=entry.getKey();
						lastProb=entry.getValue();
					}
				}
	    	}catch (Exception e) {
				e.printStackTrace();
				return null;
			}
	    	series.add(cont.getLastIteration(),lastProb);
	    	dataset.addSeries(series);
		}   
	    return dataset;
			
		
        
    }
	
    /**
     * Creates a JFreeChart for the dataset given to it and returns the Chart to be displayed in a Component
     * @param dataset
     * @return
     */
    
    private JFreeChart createChart(final XYDataset dataset) {
        
        // create the chart...
        final JFreeChart chart = ChartFactory.createXYLineChart(
            "WordComprehensionScore",      // chart title
            "iteration",                      // x axis label
            "ComprehensionScore ",                      // 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();
        
        for(int i=0;i<dataset.getSeriesCount()-1;i++){
	        renderer.setSeriesLinesVisible(i, true);
	        renderer.setSeriesShapesVisible(i, true);
        }
        
        plot.setRenderer(renderer);

        //add a 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());
                
        return chart;
        
    }
}
