package Windows;

import CalculationAndLampsSets.fluxCalculation;
import CommunicationAndSaving.propertiesFile;
import measurementThread.ThreadM;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartUtilities;
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.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import static Windows.TableWindow.flux;
import static Windows.Window.factor;
import static Windows.Window.gammaFactor;

public class GraphsWindow extends  JDialog{

    private propertiesFile properties = propertiesFile.getInstance();
    private Window window;
    private JTextField cPlaneChooser;
    private JComboBox<Integer> comboBox;
    private JCheckBox saveFileQuestion;
    private JTextField fileName;
    private JPanel buttonPanel;
    private JButton polarGraph;
    private JButton XYgraph;
    private JLabel textCplane;
    private JPanel imageSavePanel;

    public GraphsWindow(JFrame Window, Window window) throws IOException {
        super(Window, "Graphs Results", true);
        this.window = window;
        setSize(170, 300);
        getContentPane().setLayout(null);
        setResizable(false);
        setLocationByPlatform(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLayout(null);

        buttonPanel = new JPanel();
        buttonPanel.setBounds(2, 2, 150, 488);
        buttonPanel.setBackground(new Color(192, 192, 192));
        add(buttonPanel);

        polarGraph = new JButton("Polar Graph");
        polarGraph.setBounds(10, 10, 130, 30);
        polarGraph.addActionListener(new GraphsWindow.polarGraphListener());
        buttonPanel.add(polarGraph);

        XYgraph = new JButton("XY Graph");
        XYgraph.setBounds(10, 45, 130, 30);
        XYgraph.addActionListener(new GraphsWindow.xyGraphListener());
        buttonPanel.add(XYgraph);

        textCplane = new JLabel("C-Plane Selection:");
        textCplane.setBounds(10, 83, 130, 30);
        buttonPanel.add(textCplane);
        buttonPanel.setLayout(null);
        comboBox = new JComboBox<>();
        comboBox.setBounds(10, 115, 125, 30);
        buttonPanel.add(comboBox);
        if(ThreadM.getMeasurementStaticSetsForResultsWindow() != null) {
            for (int i = 0; i < ThreadM.getMeasurementStaticSetsForResultsWindow().size(); i++) {
                comboBox.addItem(i * factor);
            }
        }

        imageSavePanel = new JPanel();
        imageSavePanel.setBounds(10, 155, 125, 90);
        imageSavePanel.setBackground(new Color(105, 25, 25));
        imageSavePanel.setLayout(null);
        fileName = new JTextField();
        fileName.setBounds(5, 5, 113, 30);
        imageSavePanel.add(fileName);
        saveFileQuestion = new JCheckBox("Save IMAGE");
        saveFileQuestion.setSelected(false);
        saveFileQuestion.setBounds(5, 35, 113, 30);
        imageSavePanel.add(saveFileQuestion);
        buttonPanel.add(imageSavePanel);
    }

    private class polarGraphListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {

            if (ThreadM.getMeasurementStaticSetsForResultsWindow() != null){
                if (Double.parseDouble(comboBox.getSelectedItem().toString()) % factor == 0){

                    Integer value = (int)(Double.parseDouble(comboBox.getSelectedItem().toString()) / factor);

                    ArrayList<ArrayList<Double>> twoDimensionaArrayList = new ArrayList<>();
                    ArrayList<String> choosenList = new ArrayList<>(ThreadM.getMeasurementStaticSetsForResultsWindow().get(value));
                    ArrayList<Double> choosenListDouble = new ArrayList<>();
                    ArrayList<Double> list = new ArrayList<>();
                    ArrayList<Double> help;

                    for (String string : choosenList) {
                        if (window.getIluminationForLDT()){
                            choosenListDouble.add(Double.parseDouble(formatForEulumdatValues(string)));
                        }else if(!window.getIluminationForLDT()){
                            choosenListDouble.add(Double.parseDouble(string));
                        }
                    }

                    double increment = 0;
                    for (Double doup: choosenListDouble){
                        help = new ArrayList<>();
                        list.add(increment * gammaFactor);
                        list.add(doup);
                        help = (ArrayList<Double>) list.clone();
                        twoDimensionaArrayList.add(help);
                        list.clear();
                        increment += 1;
                    }
                    System.out.println(twoDimensionaArrayList);

                    XYSeries series = new XYSeries("Luminance Values");
                    XYDataset xyDataset;

                    for (ArrayList<Double> doubles: twoDimensionaArrayList) {
                        series.add(doubles.get(0), doubles.get(1));
                    }

                    xyDataset = new XYSeriesCollection(series);
                    JFreeChart chart = ChartFactory.createPolarChart("Polar Chart of luminosity", xyDataset,  true, true, false);
                    ChartFrame chartFrame = new ChartFrame("",chart);
                    chartFrame.setSize(750, 600);
                    chartFrame.setVisible(true);
                    setVisible(false);


                    if (saveFileQuestion.isSelected()){
                        try {
                            if (!String.valueOf(fileName.getText()).equalsIgnoreCase("") || String.valueOf(fileName.getText()) != null){
                                File file = new File(properties.get_Property("File Path") + "\\" + String.valueOf(fileName.getText()) + ".jpeg");
                                ChartUtilities.saveChartAsJPEG(file, chart, 750, 600);
                            }else{
                                JOptionPane.showMessageDialog(null, "Have to select the Image name!");
                            }
                        }catch (Exception exception){
                            JOptionPane.showMessageDialog(null, "Can not create the Image File!");
                        }
                    }
                }else{
                    JOptionPane.showMessageDialog(GraphsWindow.this, "Wrong choose, Please choose C-Plane you want to vizualize!");
                }
            }else{
                JOptionPane.showMessageDialog(null, "Can not generate the Graph!");
            }

        }
    }

    private class xyGraphListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {

            if (ThreadM.getMeasurementStaticSetsForResultsWindow() != null){
                if (Double.parseDouble(comboBox.getSelectedItem().toString()) % factor == 0){

                Integer value = (int)(Double.parseDouble(comboBox.getSelectedItem().toString()) / factor);

                ArrayList<ArrayList<Double>> twoDimensionaArrayList = new ArrayList<>();
                ArrayList<String> choosenList = new ArrayList<>(ThreadM.getMeasurementStaticSetsForResultsWindow().get(value));
                ArrayList<Double> choosenListDouble = new ArrayList<>();
                ArrayList<Double> list = new ArrayList<>();
                ArrayList<Double> help;

                for (String string : choosenList) {
                    if (window.getIluminationForLDT()){
                        choosenListDouble.add(Double.parseDouble(formatForEulumdatValues(string)));
                    }else if(!window.getIluminationForLDT()){
                        choosenListDouble.add(Double.parseDouble(string));
                    }
                }

                double increment = 0;
                for (Double doup: choosenListDouble){
                    help = new ArrayList<>();
                    list.add(increment * factor);
                    list.add(doup);
                    help = (ArrayList<Double>) list.clone();
                    twoDimensionaArrayList.add(help);
                    list.clear();
                    increment += 1;
                }
                System.out.println(twoDimensionaArrayList);

                XYSeries series = new XYSeries("Luminance Values");
                XYDataset xyDataset;

                for (ArrayList<Double> doubles: twoDimensionaArrayList) {
                    series.add(doubles.get(0), doubles.get(1));
                }

                xyDataset = new XYSeriesCollection(series);
                JFreeChart chart = ChartFactory.createXYLineChart("XYLine Chart of luminosity", "Gamma Angle", "Luminance", xyDataset, PlotOrientation.VERTICAL, true, true, false);
                ChartFrame chartFrame = new ChartFrame("",chart);
                chartFrame.setSize(750, 600);
                chartFrame.setVisible(true);
                setVisible(false);

                if (saveFileQuestion.isSelected()){
                    try {
                        if (!String.valueOf(fileName.getText()).equalsIgnoreCase("") || String.valueOf(fileName.getText()) != null){
                            File file = new File(properties.get_Property("File Path") + "\\" + String.valueOf(fileName.getText()) + ".jpeg");
                            ChartUtilities.saveChartAsJPEG(file, chart, 750, 600);
                        }else{
                            JOptionPane.showMessageDialog(null, "Have to select the Image name!");
                        }
                    }catch (Exception exception){
                        JOptionPane.showMessageDialog(null, "Can not create the Image File!");
                    }
                }
            }else{
                JOptionPane.showMessageDialog(GraphsWindow.this, "Wrong choose, Please choose C-Plane you want to vizualize!");
            }
        }else{
            JOptionPane.showMessageDialog(null, "Can not generate the Graph!");
            }
        }
    }

    private String formatForEulumdatValues(String actualValue) {
        actualValue = String.valueOf(Double.parseDouble(actualValue) * (1000/Double.valueOf(Window.getID26_lamps().get(0).ID26c_fluxOfLamp)));
        return actualValue;
    }
}

