import matplotlib.pyplot as plt
from  matplotlib import dates
import pandas as pd
from datetime import datetime
import sys

font = 14
print_width = 15
print_height = 8
plot_windows = 2
channels = [1, 0, 0, 0, 0, 0]
asotr_kit = '01'

xborders=False
begin=0;
end=0;

path = '../data/asotr/'
fname_B = f'{path}beta_2025.xlsx'

fname = 'asotr' + asotr_kit + '_data_T.csv'
fname_pow = 'asotr' + asotr_kit + '_data_P.csv'

pict_name = '../plots/' + 'ASOTR' + asotr_kit + '_flight_T_P_all' 
ox_dtime_format = '%Y.%m.%d'

legend=['BRD1', 'BRD2', 'BRD3', 'BRD4', 'плита МУП МВН, датчик1', 'плита МУП МВН, датчик 2']
width=[1, 2, 1, 1, 1, 1]

marker = ['-', '--', '-', '-', '-.', '-'];
width_arr = [1, 0.5, 0.2, 0.1, 1, 1]

data_b = pd.read_excel(fname_B, 
        sheet_name=0,
        usecols=[0,1,2], 
        header=4,
        names=['turn_num', 'beta_angle', 'timestamp'],
        parse_dates=['timestamp'],
        date_format='%Y-%m-%d %H:%M:%S')


fname = [path + fname, path + fname_pow]
data = [pd.read_csv(fname[0], sep=';', parse_dates=['timestamp'], date_format="%d.%m.%Y %H:%M:%S.%f"),
        pd.read_csv(fname[1], sep=';', parse_dates=['timestamp'], date_format="%d.%m.%Y %H:%M:%S.%f")]

ch= [[], [], [], [], [], []]
ch_signs = ["temp", "pow"]
data_dict = {"temp": ch, "pow": ch, "time": []}
data_dict["time"] = data[0]['timestamp']
col=['ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6', 'ch7']

for j in range(2):
    for index, row, in data[j].iterrows():
        for i in range(6):
            ch[i].append(float(row[col[i]]))
    data_dict[ch_signs[j]] = ch
    ch= [[], [], [], [], [], []]

len_data = [len(data_dict['temp'][0]), len(data_dict['pow'][0])]
len_ = min(len_data)

if xborders == False:
    begin = 0
    end = 320000



if plot_windows == 1:
    fig, ax = plt.subplots(figsize=(print_width, print_height), dpi=300)

    i = 0
    for elem in data_dict['temp']:
        if channels[i] == 1:
            ax.plot(data_dict['time'][begin:end], elem[begin:end], marker[i], linewidth=width[i], label=legend[i])
        i += 1

    ax.tick_params(axis="both", width=1, labelsize=font)
    ax.grid(visible=True, linestyle = 'dotted')
    ax.set_ylabel(r"Temperature, $^\circ$C", fontsize=font)
    ax.set_xlabel('Date', fontsize=font)
    ax.legend(fontsize=font)

    date_formatter = dates.DateFormatter(ox_dtime_format)
    ax.xaxis.set_major_formatter(date_formatter)

    plt.tight_layout()
    fig.savefig(pict_name)
    plt.show()

elif plot_windows == 2:

    fig = plt.figure(figsize=(print_width, print_height), dpi=600)
    ax1 = fig.add_subplot(1, 1, 1)
    # ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)

    i = 0
    for elem in data_dict['temp']:
        if channels[i] == 1:
            ax1.plot(data_dict['time'][begin:end], elem[begin:end], marker[i], linewidth=width[i], label=legend[i])
        i += 1
   
    ax3 = ax1.twinx()
    ax3.plot(data_b['timestamp'][0:3400], data_b['beta_angle'][0:3400], marker[1], color='r', linewidth=width[1], label='Beta angle')
    ax3.set_ylabel('Beta angle', fontsize=font)
    ax3.tick_params(axis="y", width=1, labelsize=font)
    ax3.legend(fontsize=font, loc='upper right')

    # i = 0
    # for elem in data_dict['pow']:
    #     if channels[i] == 1:
    #         ax2.plot(data_dict['time'][begin:end], elem[begin:end], marker[i], linewidth=width[i], label=legend[i])
    #     i += 1

    ax1.tick_params(axis="both", width=1, labelsize=font)
    ax1.grid(visible=True, linestyle = 'dotted')
    ax1.set_ylabel(r"Temperature, $^\circ$C", fontsize=font)
    ax1.set_xlabel('Date', fontsize=font)
    ax1.legend(fontsize=font, loc='lower right')

    date_formatter = dates.DateFormatter(ox_dtime_format)
    ax1.xaxis.set_major_formatter(date_formatter)

    # ax2.tick_params(axis="both", width=1, labelsize=font)
    # ax2.grid(visible=True, linestyle = 'dotted')
    # ax2.set_ylabel('Мощность, %', fontsize=font)
    # ax2.set_xlabel('Время', fontsize=font)
    # ax2.legend(fontsize=font, loc='lower right')

    # date_formatter = dates.DateFormatter(ox_dtime_format)
    # ax2.xaxis.set_major_formatter(date_formatter)

    # plt.title('automatic thermal control system ' + asotr_kit, fontsize=font)
    # plt.title('Automated  ' + asotr_kit, fontsize=font)
    plt.tight_layout()
    fig.savefig(pict_name)
    plt.show()





# asotr_kit2 = '02'
# fname2 = 'asotr' + asotr_kit2 + '_data_T.csv'
# fname_pow2 = 'asotr' + asotr_kit2 + '_data_P.csv'
# legend2=['2 БРД1', '2 БРД2', '2 БРД3', '2 БРД4', '2 плита МУП МВН, датчик1', '2 плита МУП МВН, датчик 2']

# fname2 = [path + fname2, path + fname_pow2]
# data2 = [pd.read_csv(fname2[0], sep=';', parse_dates=['timestamp'], date_parser=dateparse),
#         pd.read_csv(fname2[1], sep=';', parse_dates=['timestamp'], date_parser=dateparse)]

# ch= [[], [], [], [], [], []]
# ch_signs = ["temp", "pow"]
# data_dict2 = {"temp": ch, "pow": ch, "time": []}
# data_dict2["time"] = data2[0]['timestamp']
# col=['ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6', 'ch7']

# for j in range(2):
#     for index, row, in data2[j].iterrows():
#         for i in range(6):
#             ch[i].append(float(row[col[i]]))
#     data_dict2[ch_signs[j]] = ch
#     ch= [[], [], [], [], [], []]

# len_data2 = [len(data_dict2['temp'][0]), len(data_dict2['pow'][0])]
# len_2 = min(len_data2)

# if xborders == False:
#     begin2 = 0
#     end2 = len_2 - 1


#     i = 0
#     for elem in data_dict2['temp']:
#         if channels[i] == 1:
#             print('legend2: ' + legend2[i])
#             ax1.plot(data_dict2['time'][begin2:end2], elem[begin2:end2], marker[i], linewidth=width[i], label=legend2[i])
#         i += 1
    
    # ax2.plot(pd.Series(data_dict2['temp'][0]) - pd.Series(data_dict['temp'][0]))
 

