package graph;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import javax.swing.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PopularityLineChart extends JFrame {
    private static final long serialVersionUID = 1L;
    private static final String path = "C:\\Users\\Admin\\Desktop\\hiwi tud\\total_msgs_intervals.txt";

    public PopularityLineChart(String applicationTitle, String chartTitle) throws IOException {
        super(applicationTitle);

        // based on the dataset we create the chart
        JFreeChart pieChart = ChartFactory.createXYLineChart(chartTitle, "Round", "Number of messages", createDataset(), PlotOrientation.VERTICAL, true, true, false);

        // Adding chart into a chart panel
        ChartPanel chartPanel = new ChartPanel(pieChart);

        // settind default size
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));

        // add to contentPane
        setContentPane(chartPanel);
    }

    private XYDataset createDataset() throws IOException {
        List<XYSeries> series = new ArrayList<>();

        FileReader fr = new FileReader(path);
        BufferedReader br= new BufferedReader(fr);
        String line;
        while((line = br.readLine()) != null) {
            String[] elements = line.split("\t");
            String[] values = elements[1].split(" ");
            XYSeries aSeries = new XYSeries(elements[0]);
            for (String s : values) {
                String[] xyCoordinator = s.split("\\|");
                aSeries.add(Double.parseDouble(xyCoordinator[0]), Double.parseDouble(xyCoordinator[1]));
            }
            series.add(aSeries);
        }
        final XYSeriesCollection dataset = new XYSeriesCollection();
        for(XYSeries xys : series)
            dataset.addSeries(xys);

        return dataset;
    }

    public static void main(String[] args) throws IOException {
        PopularityLineChart chart = new PopularityLineChart("Dataset statistics", "Total number of messages from each interval");
        chart.pack();
        chart.setVisible(true);
    }
}
