import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import pandas as pd
import numpy as np
import sys
from importlib import reload
sys.path.append('./')
import asotr
reload(asotr)
from datetime import datetime, timedelta
from matplotlib import dates

def get_raw_data(year, path_with_data, asotr_kit, data_borders):

    if data_borders['flag'] == True:
        start_date = data_borders['begin'] + " 00:00:00"  
        end_date = data_borders['end'] + " 23:59:59"  
        accuracy = 'minutes'
    else:
        start_date = '01.01.' + year + " 00:00:00"
        end_date = '01.01.' + year + " 23:59:59"
        accuracy = 'hours'

    try:
        data, data_dict_borders = asotr.get_data(path_with_data, asotr_kit, 
                start_date, end_date, accuracy)

        ch_signs = ["temp", "temp_set", "pow"]
        ch = [[], [], [], [], [], []]
        data_dict = {
            "temp": ch,
            "temp_set": ch,
            "pow": ch,
            "time_temp": [],
            "time_temp_set": [],
            "time_pow": [],
        }
        
        data_dict["time_temp"] = data[0]["timestamp"]
        data_dict["time_temp_set"] = data[1]["timestamp"]
        data_dict["time_pow"] = data[2]["timestamp"]

        col = ["ch1", "ch2", "ch3", "ch4", "ch5", "ch6"]

        for j in range(len(ch_signs)):
            data_dict[ch_signs[j]] = data[j][col]

    except Exception as e:
        print(f'exception: {e}')
        raise

    try:
        fname_beta = path_with_data + 'beta_' + year + '.xlsx'
        dateparse_beta = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')

        data_beta = pd.read_excel(fname_beta, sheet_name=0, usecols=[0,1,2], header=4,
            names=['turn_num', 'beta_angle', 'timestamp'], parse_dates=['timestamp'],
            date_parser=dateparse_beta)
    except Exception as e:
        print(f'exception: {e}')
        raise

    return (data_dict, data_dict_borders, data_beta)


def plot_asotr_borders(year, path_with_data, ch, asotr_kit, data_borders, 
        font=14, save_flag=True):
    # get from files and prepare data
    print_width = 20
    print_height = 12
    width = 1
    plot_windows = 1

    channels = list(map(int, ch))

    plot_task = {"temp": 1, "temp_set": 1, "pow": 1}
    ox_dtime_format = "%d.%m.%Y"

    legend = [
        "канал 1 (БРД1)",
        "канал 2 (БРД2)",
        "канал 3 (БРД3)",
        "канал 4 (БРД4)",
        "канал 5 (плита МУП МВН)",
        "канал 6 (плита МУП МВН)",
    ]
    legend_set = list(map(lambda x: x + " уставка", legend))
    width = [1, 1, 1, 1, 1, 1]
    width_set = [3, 3, 3, 3, 3, 3]

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

    try:
        data_dict, data_dict_borders, data_beta = get_raw_data(year, path_with_data, 
                asotr_kit, data_borders)
    except Exception as e:
        print(f'{e}')
        return
    
    if plot_windows == 1:
        fig, ax = plt.subplots(figsize=(print_width, print_height), dpi=200)

        if plot_task["temp"] == 1:
            for i in range(len(channels)):
                if channels[i] == 1:
                    line, = ax.plot(data_dict_borders["time_temp"],
                            data_dict_borders['temp'].iloc[:,i],
                            '--',
                            linewidth=1,
                            label=legend[i],)

                    ax.plot(data_dict["time_temp"],
                            data_dict['temp'].iloc[:,i],
                            marker[i],
                            linewidth=width[i],
                            label=legend[i],)
                    ch = i
            
            ax.tick_params(axis="both", width=1, labelsize=font)
            ax.grid(visible=True, linestyle="dotted")
            ax.set_ylabel("Температура, $^\circ$C", fontsize=font)
            ax.set_xlabel("Время", fontsize=font)
            ax.legend(fontsize=font)

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

            ax2 = ax.twinx() 
            ax2.plot(data_beta['timestamp'], data_beta['beta_angle'], marker[4], 
                    color='r', linewidth=width[5], label='угол Бета')
            ax2.set_ylabel('Угол Бета', fontsize=font)
            ax2.tick_params(axis='y', width=1, labelsize=font)
            ax2.legend(fontsize=font, loc='lower right')

            plt.tight_layout()

            def update(val):
                shift_amount = val * pd.Timedelta(days=1)
                shifted_timestamps = data_dict_borders['time_temp'] + shift_amount
                scaled_values = data_dict_borders['temp'].iloc[:,ch] + 5
                line.set_data(shifted_timestamps, scaled_values)
                fig.canvas.draw_idle()

            slider_ax = plt.axes([0.25, 0.05, 0.65, 0.03])
            slider = Slider(slider_ax, 'Shift days', -100, 100, valinit=0)
            slider.on_changed(update)

            plt.show()


            if save_flag == True:
                pict_name = (f'../plots/reports/ASOTR{asotr_kit}_flight_T_P_{asotr.convert_to_str(channels)}_{data_borders["begin"][0:5].replace(".", "")}_{data_borders["end"][0:5].replace(".", "")}_{data_borders["end"][6:]}.png')
                fig.savefig(pict_name)


ch = '100000'
year = '2025'
path_with_data = '../data/asotr/'
asotr_kit = '01'
data_borders = {'flag': True, 'begin': '15.03.2025', 'end': '01.05.2025'}

plot_asotr_borders(year, path_with_data, ch, asotr_kit, data_borders, font=6, save_flag=True)

