import itertools as itt
import sys
import re
import time
import datetime
import serial
import win32event
import win32file
import win32api
import pywintypes
import subprocess
import matplotlib
import numpy as np
from sklearn.linear_model import LinearRegression
from scipy.signal import butter, filtfilt

freq = 3000000
sample_rate = 2000000
amp = 1
xgain = 35
rf_filename = "test_linreg.bin"
port = 11
adc_filename = "pico_params.xml"
below_trigger = False
sync_filename = "Sync_param.xml"
pico_rate = 80e6

# sample rate - 1st element
# period - 2nd element
# inverse duty cycle - 3rd element
# number - 4th element

def load_csv(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            cleaned_lines = []
            for line in f:
                line = line.strip()
                if line.endswith(','):
                    line = line[:-1]
                cleaned_lines.append(line)
            f.close()

        loaded_array = np.loadtxt(cleaned_lines, delimiter=',')
        if loaded_array.ndim == 1:
            loaded_array = loaded_array.reshape(-1, 1)

        return loaded_array
    except Exception as e:
        print(f"Could not load file:\n{e}")
        return -1

ls_tup = [
    list(item)
    for item in itt.product(
        range(1, 5),
        range(1, 8),
        range(1, 6),
        range(1, 5)
    )
]
ls_ls = []

for tup in ls_tup:
    ls_ls.append(list(tup))

for x in ls_ls: 
    if x[0] == 1: # sr in MHz
        x[0] = 2
    elif x[0] == 2:
        x[0] = 8
    elif x[0] == 3:
        x[0] = 10
    elif x[0] == 4:
        x[0] = 20

    if x[1] == 1: # period in ms
        x[1] = 0.24
    elif x[1] == 2:
        x[1] = 0.48
    elif x[1] == 3:
        x[1] = 0.96
    elif x[1] == 4:
        x[1] = 1.92
    elif x[1] == 5:
        x[1] = 3.84
    elif x[1] == 6:
        x[1] = 7.68
    elif x[1] == 7:
        x[1] = 11.52

    if x[2] == 1: # idc
        x[2] = 1.5
    elif x[2] == 2:
        x[2] = 2
    elif x[2] == 3:
        x[2] = 4
    elif x[2] == 4:
        x[2] = 8
    elif x[2] == 5:
        x[2] = 10

    if x[3] == 1: # time in sec
        x[3] = 100
    elif x[3] == 2:
        x[3] = 200
    elif x[3] == 3:
        x[3] = 400
    elif x[3] == 4:
        x[3] = 800

    x.append(x[1]*x[3])

print(f"Num mes: {len(ls_ls) * 3}")

res = 0
y = np.array([])

with open('delays.txt', 'r', encoding='utf-8') as f:
    cleaned_lines = []
    for line in f:
        res = re.split(r'[=;\n ]', line)
        for item in res:
            if item == 'delay':
                print(f'Delay: {float(res[4]) / 2}')
                y = np.append(y, [float(res[4]) / 2])
    f.close()

for i in range(0, len(ls_ls)):
    with open('delays_updated.txt', 'a', encoding='utf-8') as f:
        f.write(f'sr = {ls_ls[i][0]} MHz; period = {ls_ls[i][1]} ms; idc = {ls_ls[i][2]}; time = {ls_ls[i][3]} s;\ndelay = {y[i]} nS;\n')
        f.close()

print(np.size(y))

reg = LinearRegression().fit(np.array(ls_ls), y)
scr = reg.score(np.array(ls_ls), y)
print('Coef: ', reg.coef_)
print('Intercept: ', reg.intercept_)
with open('regression5.txt', 'w', encoding='utf-8') as f:
        f.write(f'score = {scr};\nsr_coef = {reg.coef_[0]};\nperiod_coef = {reg.coef_[1]} ns/ms;\nidc_coef = {reg.coef_[2]};\nnum_coef = {reg.coef_[3]} ns/num;time_coef = {reg.coef_[4]} ns/ms;\nintercept = {reg.intercept_}\n\n')
        f.close()