import random
from pathlib import Path
from sys import exit, stderr, float_info
from os import listdir
import scipy.signal
import numpy as np


import matplotlib.pyplot as plt


class ExperimentWorkerModule:
    __specimen_folder_path = None
    __experiment_folder_path = None
    # __out_folder_path = Path("M:\\School\\UK\\RP\\python project\\RP\\testNewClass\\out")

    __lag = None
    __highest_val = float_info.min
    __specimen_id = -1
    __graph_color = "g"

    __specimen_names = []
    __experiment_names = []

    # pass full path, both arguments as string e.g. "C://test/test/testfile.txt"
    def __init__(self, specimen_folder_path, experiment_path):
        self.__experiment_folder_path = Path(experiment_path)
        self.__specimen_folder_path = Path(specimen_folder_path)

    def run_experiment(self):

        try:
            self.__experiment_names = self.__get_experiment_names()
            self.__specimen_names = self.__get_specimen_names()

            for experiment_number in range(0, len(self.__experiment_names)):
                current_experiment_file_path = Path(self.__experiment_folder_path)
                current_experiment_file_path = current_experiment_file_path / self.__experiment_names[experiment_number]

                print("\nStarted experiment: " + str(current_experiment_file_path), file=stderr)
                # open experiment file
                current_experiment_file = open(current_experiment_file_path, "r")
                current_experiment_file_data = self.__read_file_data(current_experiment_file)
                current_experiment_file.close()

                for specimen_number in range(0, len(self.__specimen_names)):
                    # if self.__specimen_names[specimen_number] == "specimen_013_luminance.txt":
                    # if self.__specimen_names[specimen_number] == "specimen_025_luminance.txt":
                    if self.__specimen_names[specimen_number] == "specimen_045_luminance.txt":
                         self.__graph_color = "r"
                    else:
                         self.__graph_color = "g"

                    current_specimen_file_path = Path(self.__specimen_folder_path)
                    current_specimen_file_path = current_specimen_file_path / self.__specimen_names[specimen_number]

                    print("\tProcessing: " + str(current_specimen_file_path), file=stderr)
                    # open specimen file
                    current_specimen_file = open(current_specimen_file_path, "r")
                    current_specimen_file_data = self.__read_file_data(current_specimen_file)
                    current_specimen_file.close()

                    function_result = self.__process_selected(current_experiment_file_data, current_specimen_file_data)
                    if function_result[0] > self.__highest_val:
                        self.__highest_val = function_result[0]
                        self.__lag = function_result[1]
                        self.__specimen_id = specimen_number

                print("Experiment: %s contains %s with value %f and lag %d" % (
                self.__experiment_names[experiment_number], self.__specimen_names[self.__specimen_id],
                self.__highest_val, self.__lag), file=stderr)
                self.__lag = None
                self.__highest_val = float_info.min
                self.__specimen_id = -1

        except OSError:
            print("Couldn't open files. Check whether they really exist or whether paths are valid", file=stderr)
            exit(-1)

    def __process_selected(self, selected_experiment_data, selected_specimen_data):
        n1 = np.array(selected_experiment_data, dtype=float)
        n2 = np.array(selected_specimen_data, dtype=float)
        correlated = scipy.signal.correlate(n1, n2, mode="valid")
        correlated_lag = scipy.signal.correlation_lags(n1.size, n2.size, mode="valid")

        cislo = np.argmax(correlated)
        h_val = correlated[cislo]
        lag = correlated_lag[np.argmax(correlated)]

        plt.plot(correlated_lag, correlated, color=self.__graph_color)
        plt.show()
        print("\tvalue %f and lag %d" % (h_val, lag), file=stderr)
        return_data = [h_val, lag]
        return return_data
        # print("\t\tLag = %d, Highest_value = %f"%(lag, result[h_val]), file=stderr)
        # print("\t\tResult: %s" % (str(result)), file=stderr)
        # print("\t\tdone", file=stderr)

        # result.append(float(0))
        # print("\t\tExperiment: %s" % selected_experiment_data, file=stderr)
        # print("\t\tSpecimen: %s" % selected_specimen_data, file=stderr)

    def __get_specimen_names(self):
        files = listdir(self.__specimen_folder_path)
        return files

    def __get_experiment_names(self):
        files = listdir(self.__experiment_folder_path)
        return files

    def __read_file_data(self, file):
        data = []
        for line in file.read().splitlines():
            data.append(line)
        return data

