package rs.fon.is.weka.clustering;

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;

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.axis.NumberTickUnit;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

public class ElbowMethodPlot extends JFrame {
	
	private static final long serialVersionUID = 1L;

	public ElbowMethodPlot(int[] kValues, double[] sseValues) {
		
        super("Elbow Method Chart");
 
        JPanel chartPanel = createChartPanel(kValues, sseValues);
        add(chartPanel, BorderLayout.CENTER);
 
        setSize(640, 480);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }
 
    private JPanel createChartPanel(int[] k, double[] sse) {
        
    	String chartTitle = "Elbow Method Chart";
        String xAxisLabel = "K";
        String yAxisLabel = "Sum of Squared Errors";
     
        XYDataset dataset = createDataset(k, sse);
     
        JFreeChart chart = ChartFactory.createXYLineChart(chartTitle,
                xAxisLabel, yAxisLabel, dataset);
        
        NumberAxis xAxis = new NumberAxis();
        xAxis.setTickUnit(new NumberTickUnit(1));
        xAxis.setLowerBound(k[0]);
        xAxis.setUpperBound(k[k.length-1]);
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setDomainAxis(xAxis);
        
        plot.setBackgroundPaint(Color.WHITE);
     
        return new ChartPanel(chart);
        
    }
 
    private XYDataset createDataset(int[] kValues, double[] sseValues) {
        
    	XYSeriesCollection dataset = new XYSeriesCollection();
        XYSeries series = new XYSeries("K-Means");
        
        for (int i = 0; i < sseValues.length; i++) {
			series.add(kValues[i], sseValues[i]);
		}
        dataset.addSeries(series);
   
        return dataset;
    }
 
    public void drawPlot() {
        this.setVisible(true);
    }

}
