import matplotlib.pyplot as plt
from matplotlib import dates
import argparse
import sys
from importlib import reload
sys.path.append('./')
import asotr
reload(asotr)
import pandas as pd

def plot_asotr_borders(path_with_data, ch, asotr_kit, begin, end, font=16, 
        plot_windows=1, width_=2, lang='ru', time_format='%d.%m.%Y', 
        show_flag=False, cmd=0):
    print_width = 20
    print_height = 12

    channels = list(map(int, ch))
    pict_name = (f'../plots/reports/ASOTR{asotr_kit}_flight_T_P_{asotr.convert_to_str(channels)}_{begin[0:5].replace(".", "")}_{end[0:5].replace(".", "")}.png')

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

    if lang == 'ru':
        legend = [
            "канал 1 (БРД1)",
            "канал 2 (БРД2)",
            "канал 3 (БРД3)",
            "канал 4 (БРД4)",
            "канал 5 (плита МУП МВН)",
            "канал 6 (плита МУП МВН)",
        ]
    else:
        legend = [
            "channel 1 (BRD1)",
            "channel 2 (BRD2)",
            "channel 3 (BRD3)",
            "channel 4 (BRD4)",
            "channel 5 (DCM landing place)",
            "channel 6 (DCM landing place)",
        ]
        
    if lang == 'ru':
        legend_set = list(map(lambda x: x + " уставка", legend))
    else:
        legend_set = list(map(lambda x: x + " setpoint", legend))
    width = [width_, width_, width_, width_, width_, width_]
    width_set = [3, 3, 3, 3, 3, 3]

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

    # get from files and prepare data
    start_date = begin.replace('_', ' ')
    end_date = end.replace('_', ' ')
    try:
        data, data_dict = asotr.get_data(path_with_data, asotr_kit, start_date, end_date, 'minutes')
    except Exception as e:
        return
    
    if plot_windows == 1:
        fig, ax = plt.subplots(figsize=(print_width, print_height), dpi=300)

        if plot_task["temp"] == 1:
            for i in range(len(channels)):
                if channels[i] == 1:
                    ax.plot(data_dict["time_temp"],
                            data_dict['temp'].iloc[:,i],
                            marker[i],
                            linewidth=width[i],
                            label=legend[i],)
            
            ax.tick_params(axis="both", width=1, labelsize=font)
            ax.grid(visible=True, linestyle="dotted")
            if lang == 'ru':
                ax.set_ylabel(r"Температура, $^\circ$C", fontsize=font)
                ax.set_xlabel("Время", fontsize=font)
            else:
                ax.set_ylabel(r"Temperature, $^\circ$C", fontsize=font)
                ax.set_xlabel("Time", 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)
            print(f'figure saved: {pict_name}')
            if show_flag == True: 
                plt.show()

    elif plot_windows == 2:

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

        if cmd == '1':
            try:
                cmd_human = pd.read_csv('../data/cmd_asotr/cmd_human.csv', 
                    delimiter=';', names=['timestamp', 'cmd'])
            except Exception as e:
                print(f'Error parsing file: {e}')
                return
            
            max_temp = max(data_dict['temp'].iloc[:,1])
            min_temp = min(data_dict['temp'].iloc[:,1])
            # print(cmd_human)
            step = 0
            for i, row in cmd_human.iterrows():
                row_time = row['timestamp'][0:len(row['timestamp']) - 4]
                # print(row_time)
                idx = asotr.find_best_time_idx(data_dict['time_temp'], 
                    row_time, accuracy='minutes')

                # print(idx)
                if idx != -1:
                    ax1.axvline(x = data_dict['time_temp'][idx], color='r', 
                            linestyle='-.')
                    ax1.text(data_dict['time_temp'][idx], max_temp - step, row['cmd'], 
                            rotation=45, va='bottom', fontsize=font)
                    step += (max_temp - min_temp)/20 
        
        if plot_task["temp"] == 1:
            for i in range(len(channels)):
                if channels[i] == 1:
                    ax1.plot(data_dict["time_temp"],
                            data_dict['temp'].iloc[:,i],
                            marker[i],
                            linewidth=width[i],
                            label=legend[i],)

        if plot_task["temp_set"] == 1:
            for i in range(len(channels)):
                if channels[i] == 1:
                   ax1.plot(data_dict["time_temp_set"],
                            data_dict['temp_set'].iloc[:,i],
                            marker[i],
                            linewidth=width_set[i],
                            label=legend_set[i],)

        if plot_task["pow"] == 1:
            for i in range(len(channels)):
                if channels[i] == 1:
                    ax2.plot(data_dict["time_pow"],
                            data_dict['pow'].iloc[:,i],
                            marker[i],
                            linewidth=width[i],
                            label=legend[i],)

        ax1.tick_params(axis="both", width=1, labelsize=font)
        ax1.grid(visible=True, linestyle="dotted")

        if lang == 'ru':
            ax1.set_ylabel(r"Температура, $^\circ$C", fontsize=font)
            ax1.set_xlabel("Время", fontsize=font)
        else:
            ax1.set_ylabel(r"Temperature, $^\circ$C", fontsize=font)
            ax1.set_xlabel("Time", fontsize=font)

        ax1.legend(fontsize=font)   

        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")
        if lang == 'ru':
            ax2.set_ylabel("Мощность, %", fontsize=font)
            ax2.set_xlabel("Время", fontsize=font)
        else:
            ax2.set_ylabel("Power, %", fontsize=font)
            ax2.set_xlabel("Time", fontsize=font)
        ax2.set_ylim(-5,105)
        
        ax2.legend(fontsize=font)

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

        if lang == 'ru':
            title = (f'работа АСОТР{asotr_kit} в период с {start_date[0:10]} по {end_date[0:10]} г.')
        # else:
            # title = (f'work of the ATCS{asotr_kit} in the period from {start_date[0:10]} to {end_date[0:10]} г.')
        # fig.suptitle(title, fontsize=font)
        plt.tight_layout()
        fig.savefig(pict_name)
        print(f'figure saved: {pict_name}')
        if show_flag == True:
            plt.show()

if __name__ == '__main__':
    argparser = argparse.ArgumentParser("plot_flight_borders.py")

    argparser.add_argument('-s', '--source', required=True,
            help='type path with asotr csv data')
    argparser.add_argument('-c', '--channel', required=True, 
            help='type channel (example: 000011)')
    argparser.add_argument('-a', '--asotr', required=True, 
            help='type asotr kit (01 or 02)')
    argparser.add_argument('-b', '--begin', required=True, 
            help='type begin date if dd.mm.YYYY format')
    argparser.add_argument('-e', '--end', required=True, 
            help='type end date if dd.mm.YYYY format')
    argparser.add_argument('-f', '--font', required=False, 
            help='type font size (from 1 to 30)')
    argparser.add_argument('-d', '--cmd', required=False, 
            help='type display commands flag (0 or 1)')
    argparser.add_argument('-p', '--plot', required=False, 
            help='display data in plot flag (0 or 1)')
    argparser.add_argument('-w', '--plotwindows', required=False,
            help='plot counts in window (1 or 2)')
    argparser.add_argument('-l', '--linewidth', required=False,
            help='line width in plot (1, 2, ...)')
    argparser.add_argument('-t', '--timeformat', required=False,
            help='specify the time format, for example: %d.%m.%Y')
    argparser.add_argument('-g', '--language', required=False,
            help='type language, for example: ru, eng')
    
    args = argparser.parse_args()
    
    # plot_asotr_borders(args.source, args.channel, args.asotr, args.begin, args.end, 
    #         args.font, args.cmd, show_flag=args.plot, plot_windows=int(args.plotwindows),
    #         width_=int(args.linewidth), time_format = args.timeformat)
    
    plot_asotr_borders(args.source, args.channel, args.asotr, args.begin, args.end,
            font=args.font, plot_windows=int(args.plotwindows), width_=int(args.linewidth),
            lang=args.language, time_format=args.timeformat)
