/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mycommon;


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.geom.Ellipse2D;
import org.jfree.data.xy.*;//needed for XYSeries, could have called directly
import org.jfree.chart.*;//needed for createXYLineChart
import java.awt.image.*;//needed for Buffered Image
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.SeriesRenderingOrder;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYDotRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;

/**
 *
 * @author ykil
 */
public class JFreeChartsUtils {

    public static BufferedImage test () {
        int n_points = 100;
        double[] y_of_x;
        double[] x;
        StandardChartTheme them = new StandardChartTheme("JFree");
//        them.setPlotBackgroundPaint(paint);

        y_of_x = new double[n_points];
        x = new double[n_points];
        XYSeries series = new XYSeries("Cos(x) versus x");
        for (int i = 0; i < n_points; i++) {//calculate the data to be plotted
            y_of_x[i] = Math.cos(i * Math.PI / 180);
            series.add((double) i, y_of_x[i]);//add the computed values to the series
        }
        XYDataset dataset = new XYSeriesCollection(series);
        JFreeChart chart = ChartFactory.createScatterPlot("TT", "xlabel", "ylabel", dataset, org.jfree.chart.plot.PlotOrientation.VERTICAL, false, false, false);
//        chart.setBackgroundPaint(Color.white);
        chart.getPlot().setBackgroundPaint(Color.white);
        final XYPlot plot = chart.getXYPlot();
        XYDotRenderer dotz = new XYDotRenderer();
        dotz.setDotWidth(2);
        dotz.setDotHeight(2);
        plot.setRenderer(dotz);

//        dotz.setBasePaint(Color.BLACK);
//        dotz.setBaseFillPaint(Color.BLUE);
//        plot.setRenderer(0, dotz, true);

        BufferedImage image = chart.createBufferedImage(400, 400);
        return image;
    }

    private static double [] getCoeffs(String coeffString) {
        double coeffs[] = {0,0,0};
        String [] slist = coeffString.trim().split("\\s+");
        if (slist.length != 3) {
            return coeffs;
        }

        coeffs[0] = Double.parseDouble(slist[0]);
        coeffs[1] = Double.parseDouble(slist[1]);
        coeffs[2] = Double.parseDouble(slist[2]);
        return coeffs;
    }

    public static XYSeries read_points(String fName, String title) {
        double x=0,y=0;

        XYSeries series = new XYSeries(title);
        try {
            String line;
            BufferedReader in = new BufferedReader(new FileReader(fName));
            while ((line = in.readLine()) != null) {
                int count = 0;
                StringTokenizer st = new StringTokenizer(line);
                if (st.hasMoreTokens()) {
                  String token = st.nextToken();
                  x = Double.parseDouble(token);
                  count++;
                }
                if (st.hasMoreTokens()) {
                  String token = st.nextToken();
                  y = Double.parseDouble(token);
                  count++;
                }
                if (count == 2) {
                    series.add(x,y);
                }
//                String [] xy = line.split("[\\s]+");
//                System.err.println(xy.toString());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace(System.err);
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
        return series;
    }

    public static String read_coeffs_file(String fName) {
        try {
            String line;
            BufferedReader in = new BufferedReader(new FileReader(fName));
            while ((line = in.readLine()) != null) {
                if (line.length() > 3) {
                    return line;  //assume first line is 
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace(System.err);
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
        return "0 0 0";
    }

    public static XYSeries read_coeffs(String coeffs, String title, double minx, double maxx) {
        XYSeries series2 = new XYSeries(title);
        double [] cc = getCoeffs(coeffs);

        double x, y, inc = (maxx-minx)/500.0f;
        for (x = minx; x < maxx; x += inc) {  //x <= maxx causes infinite loop if minx=maxx
            y = cc[0]*x*x + (0.0+cc[1])*x + cc[2];
            series2.add(x, -y);
        }
        return series2;
    }

    public static BufferedImage make_scatter_plot_old(String fName, String coeffs, String fDebugName, String title, String xlabel, String ylabel) {

        boolean debug = fDebugName.length() > 0;
        //Get data
        XYSeries seriesData = read_points(fName, title);
        double minx=0, maxx = 0;
        if (!seriesData.isEmpty()) {
            minx = seriesData.getMinX();
            maxx = seriesData.getMaxX();
        }
        XYSeries seriesCoeffs = read_coeffs(coeffs, "Recalibration curve", minx, maxx);

        //Setup series collection
        XYSeriesCollection dataset = new XYSeriesCollection();
        dataset.addSeries(seriesCoeffs);
        dataset.addSeries(seriesData);

        if (debug) {
            XYSeries sData = read_points(fDebugName+".firstpass", "debug points");
            String coeffsStr = read_coeffs_file(fDebugName+".firstpass.coeffs");
            XYSeries sCoeffs = read_coeffs(coeffsStr, "debug curve", minx, maxx);
            dataset.addSeries(sData);
            dataset.addSeries(sCoeffs);
        }

//        JFreeChart chart = ChartFactory.createScatterPlot(title, xlabel, ylabel, dataset, org.jfree.chart.plot.PlotOrientation.VERTICAL, false, false, false);
        final JFreeChart chart = ChartFactory.createXYLineChart(
            title,      // chart title
            xlabel,                      // x axis label
            ylabel,                      // y axis label
            dataset,                  // data
            org.jfree.chart.plot.PlotOrientation.VERTICAL,
            debug,                     // include legend
            true,                     // tooltips
            false                     // urls
        );

        final XYPlot plot = chart.getXYPlot();
        plot.setSeriesRenderingOrder(SeriesRenderingOrder.FORWARD);
//        plot.setSeriesRenderingOrder(SeriesRenderingOrder.REVERSE);
        plot.setBackgroundPaint(Color.white);
//        plot.setForegroundAlpha(0.8f);

        double size = 1;
        final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        int dataindex = 1, coeffindex = 0;

//        renderer.setSeriesFillPaint(0, new Color(255, 200, 0));
        renderer.setSeriesLinesVisible(dataindex, false);
        renderer.setSeriesShape(dataindex, new Ellipse2D.Double(-size,-size,size*2,size*2));

        renderer.setSeriesLinesVisible(coeffindex, true);
        renderer.setSeriesShapesVisible(coeffindex, false);
        renderer.setSeriesStroke(coeffindex,  new BasicStroke(4.0f));

        if (debug) {
            renderer.setSeriesLinesVisible(0+2, false);
            renderer.setSeriesShape(0+2, new Ellipse2D.Double(-size,-size,size*2,size*2));

            renderer.setSeriesLinesVisible(1+2, true);
            renderer.setSeriesShapesVisible(1+2, false);

            renderer.setSeriesStroke(1+2,  new BasicStroke(2.0f));
        }

        plot.setRenderer(renderer);

        BufferedImage image = chart.createBufferedImage(400, 400);
        return image;
    }

    public static JFreeChart make_scatter_plot_core(XYDataset dataPoints, XYDataset dataFit, XYDataset dataPoints2, XYDataset dataFit2, String title, String xlabel, String ylabel) {
       //points
        XYLineAndShapeRenderer renderer1 = new XYLineAndShapeRenderer(true, false);
        double size = 1;
        renderer1.setSeriesLinesVisible(0, true);
        renderer1.setSeriesShapesVisible(0, false);
        renderer1.setSeriesStroke(0, new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

        NumberAxis xAxis = new NumberAxis(xlabel);
        xAxis.setAutoRangeIncludesZero(false);
        NumberAxis yAxis = new NumberAxis(ylabel);

        final XYPlot plot = new XYPlot(dataFit, xAxis, yAxis, renderer1);

        //curve
        XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(true, false);
        renderer2.setSeriesLinesVisible(0, false);
        renderer2.setSeriesShapesVisible(0, true);
        renderer2.setSeriesShape(0, new Ellipse2D.Double(-size,-size,size*2,size*2));

        plot.setDataset(1, dataPoints);
        plot.setRenderer(1, renderer2);

        size = size * 2.5;
        XYLineAndShapeRenderer renderer2b = new XYLineAndShapeRenderer(true, false);
        renderer2b.setSeriesLinesVisible(0, false);
        renderer2b.setSeriesShapesVisible(0, true);
        renderer2b.setSeriesShape(0, new Ellipse2D.Double(-size,-size,size*2,size*2));

        XYLineAndShapeRenderer renderer1b = new XYLineAndShapeRenderer(true, false);
        renderer1b.setSeriesLinesVisible(0, true);
        renderer1b.setSeriesShapesVisible(0, false);
        renderer1b.setSeriesStroke(0, new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
//        renderer1b.setBaseFillPaint(Color.MAGENTA);

        if (dataFit2 != null && dataPoints2 != null) {
            plot.setDataset(3, dataFit2);
            plot.setRenderer(3, renderer1b);

            plot.setDataset(2, dataPoints2);
            plot.setRenderer(2, renderer2b);
        }

        plot.setBackgroundPaint(Color.white);
        plot.setForegroundAlpha(0.65f);

        JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
        chart.setBackgroundPaint(Color.white);
        return chart;
    }

    public static BufferedImage make_scatter_plot(String fName, String coeffs, String fDebugName, String title, String xlabel, String ylabel) {

        boolean debug = fDebugName.length() > 0;
        //Get data
        XYSeries seriesData = read_points(fName, title);
        double minx=0, maxx = 0;
        if (!seriesData.isEmpty()) {
            minx = seriesData.getMinX();
            maxx = seriesData.getMaxX();
        }
        XYSeries seriesCoeffs = read_coeffs(coeffs, "Recalibration curve", minx, maxx);

        XYSeries debugData = null, debugCoeffs = null;
        if (debug) {
            debugData = read_points(fDebugName+".firstpass", "debug points");
            String coeffsStr = read_coeffs_file(fDebugName+".firstpass.coeffs");
            debugCoeffs = read_coeffs(coeffsStr, "debug curve", minx, maxx);
        }

        XYDataset dataset1 = new XYSeriesCollection(seriesData);
        XYDataset dataset2 = new XYSeriesCollection(seriesCoeffs);

        XYDataset dataset3 = null;
        if (debugData != null)
            dataset3 = new XYSeriesCollection(debugData);

        XYDataset dataset4 = null;
        if (debugCoeffs != null)
            dataset4 = new XYSeriesCollection(debugCoeffs);

        JFreeChart chart = make_scatter_plot_core(dataset1, dataset2, dataset3, dataset4, title, xlabel, ylabel);

        BufferedImage image = chart.createBufferedImage(400, 400);
        return image;
    }

}

//parent_coeffs+

//        CategoryPlot p = chart.getCategoryPlot();
//        p.setBackgroundPaint(Color.white);

//        JFreeChart chart = ChartFactory.createXYLineChart(
//                "Cos(x) versus x",
//                "x",
//                "cos(x)",
//                dataset,
//                org.jfree.chart.plot.PlotOrientation.VERTICAL,
//                true,
//                false,
//                false);
