package main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.StringTokenizer;

class ExpRunListener implements ActionListener {
    StartApplet applet;
    int indicators_array[];
    int entered_p[];
    int count_p;
    double[] coef_AR;

    public ExpRunListener(StartApplet applet) {
        this.applet = applet;
    }
    
    public void actionPerformed(ActionEvent e) {
        try {
            int start_month = applet.exp_start_month_Box.getSelectedIndex();
            String start_day = applet.exp_start_day_Field.getText();
            String start_year = applet.exp_start_year_Field.getText();
            int end_month = applet.exp_end_month_Box.getSelectedIndex();
            String end_day = applet.exp_end_day_Field.getText();
            String end_year = applet.exp_end_year_Field.getText();
    
            indicators_array = new int[8];
            if (applet.data_mean_CheckBox.isSelected()) indicators_array[0] = 1;
            if (applet.data_standard_CheckBox.isSelected()) indicators_array[1] = 1;
            if (applet.MAE_CheckBox.isSelected()) indicators_array[2] = 1;
            if (applet.MAPE_CheckBox.isSelected()) indicators_array[3] = 1;
            if (applet.PMAD_CheckBox.isSelected()) indicators_array[4] = 1;
            if (applet.MSE_CheckBox.isSelected()) indicators_array[5] = 1;
            if (applet.RMSE_CheckBox.isSelected()) indicators_array[6] = 1;
            if (applet.residual_variance_CheckBox.isSelected()) indicators_array[7] = 1;
            
            int count_indicators = 0;
            for (int i = 0; i < indicators_array.length; i++)
                if ( indicators_array[i] == 1 ) count_indicators++;
            System.out.println("count indicators = " + count_indicators);
            
            //System.out.println(applet.exp_p_Area.getText());
            if (!applet.exp_p_Area.getText().equals("")) { //jeigu duomenis nuskaitom iš textArea lauko
                String line = applet.exp_p_Area.getText();
                StringTokenizer t = new StringTokenizer(line, "\n");
                count_p = t.countTokens();
                entered_p = new int[count_p];
                int k = 0;
                while (t.hasMoreTokens()) {
                    entered_p[k] = Integer.parseInt(t.nextToken());
                    k++;
                }
                System.out.println("count p = " + count_p);
            }
            
            String[] symbol = {"GOOG", "AAPL"};
            for (int i = 0; i < symbol.length; i++) {
                for (int j = 0; j < count_p; j++) {
                    URL yahooUrl = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + symbol[i] +
                        "&a=" + start_month + "&b=" + start_day + "&c=" + start_year +
                        "&d=" + end_month + "&e=" + end_day + "&f=" + end_year + "&g=d&ignore=.csv");
                    URLConnection yc = yahooUrl.openConnection();
                    CSVFileReader csv = new CSVFileReader(new InputStreamReader(yc.getInputStream()));
                    csv.ReadFileFromURL();
                    ArrayList<String> a = csv.getArrayList();
                    String data[][] = new String[a.size()-1][7]; //duomenys
                    double data2[] = new double[a.size()-1];
                    double forecast[] = new double[a.size()-1];
                    double errors[] = new double[a.size()-1-entered_p[j]];
                    double training_error_sum = 0;
                    double bendra_suma2 = 0;
                    double bendra_suma3 = 0;
                    double bendra_suma4 = 0;
                    for (int k = 1; k < a.size(); k++) {
                        data[k-1] = a.get(k).split(",");
                        data2[a.size()-k-1] = Double.parseDouble(data[k-1][6]);
                    }
                    
                    AR_method ar_ = null;
                    ar_ = new AR_method(data2, entered_p[j]);
                    coef_AR = ar_.rezult();
                    
                    for (int m = entered_p[j]; m < data2.length; m++) {
                        for (int n = 0; n < coef_AR.length; n++) {
                             forecast[m] += coef_AR[n] * data2[m-n-1];
                        }
                        double error = data2[m] - forecast[m];
                        if ( error < 0 ) error = error*(-1);
                        errors[m-entered_p[j]] = error;
                        training_error_sum += error;
                        bendra_suma2 += error / data2[m];
                        bendra_suma3 += data2[m];
                        bendra_suma4 += error * error;
                        //System.out.println( "data2[" + m + "] = " + data2[m] + " => forecast[" + m + "] = " + forecast[m] );
                    }
                    
                    //for (int n = 0; n < errors.length; n++)
                         //System.out.println("errors["+n+"] = " + errors[n]);
                    
                    double data_mean = 0;
                    double training_data_sum = 0, training_data_sum2 = 0;
                    for (int m = 0; m < data2.length; m++) {
                        training_data_sum += data2[m];
                        training_data_sum2 += data2[m]*data2[m];
                    }
                    data_mean = training_data_sum / data2.length;
                    if (applet.data_mean_CheckBox.isSelected()) System.out.println("Data mean = " + applet.round(data_mean, 3));

                    double data_variance = 0;
                    data_variance = (training_data_sum2 - ((training_data_sum*training_data_sum)/data2.length)) / (data2.length - 1);
                    if (applet.data_standard_CheckBox.isSelected()) System.out.println("Data variance = " + applet.round(data_variance, 3));

                    double MAE = 0;
                    if (training_error_sum == Double.NaN || training_error_sum == Double.POSITIVE_INFINITY || training_error_sum == Double.NEGATIVE_INFINITY ||
                        training_error_sum == 0.0)
                        MAE = 0;
                    else MAE = training_error_sum / errors.length;
                    if (applet.MAE_CheckBox.isSelected()) System.out.println("MAE = " + applet.round(MAE, 3));

                    double MAPE = 0;
                    if (bendra_suma2 == Double.NaN || bendra_suma2 == Double.POSITIVE_INFINITY || bendra_suma2 == Double.NEGATIVE_INFINITY ||
                        training_error_sum == 0.0)
                        MAPE = 0;
                    else MAPE = bendra_suma2 / errors.length;
                    if (applet.MAPE_CheckBox.isSelected()) System.out.println("MAPE = " + applet.round(MAPE, 3));

                    double PMAD = 0;
                    if (training_error_sum == Double.NaN || training_error_sum == Double.POSITIVE_INFINITY || training_error_sum == Double.NEGATIVE_INFINITY ||
                        bendra_suma3 == Double.NaN || bendra_suma3 == Double.POSITIVE_INFINITY || bendra_suma3 == Double.NEGATIVE_INFINITY ||
                        training_error_sum == 0.0 || bendra_suma3 == 0.0)
                            PMAD = 0;
                    else PMAD = training_error_sum / bendra_suma3;
                    if (applet.PMAD_CheckBox.isSelected()) System.out.println("PMAD = " + applet.round(PMAD, 3));

                    double MSE = 0;
                    if (bendra_suma4 == Double.NaN || bendra_suma4 == Double.POSITIVE_INFINITY || bendra_suma4 == Double.NEGATIVE_INFINITY ||
                        bendra_suma4 == 0.0)
                        MSE = 0;
                    else MSE = bendra_suma4 / errors.length;
                    if (applet.MSE_CheckBox.isSelected()) System.out.println("MSE = " + applet.round(MSE, 3));

                    /*double RMSE = 0;
                    if (MSE == 0.0) RMSE = 0;
                    else RMSE = Math.sqrt(MSE);
                    RMSE_value_AR_Label.setText(" = " + Double.toString(round(RMSE, 3)));

                    double residual_variance = 0;
                    if ( count-1 > 0 ) residual_variance = (bendra_suma4 - ((bendra_suma5*bendra_suma5)/count)) / (count - 1);
                    else residual_variance = 0;
                    residual_variance_value_AR_Label.setText(" = " + Double.toString(round(residual_variance, 3)));*/
                } 
            }
        }
        catch(Exception ex) {
            System.out.println("Unable to run experiment: " + ex);
        }
    }
}