import sys
from importlib import reload
sys.path.append('./')
import asotr
reload(asotr)
import pandas as pd
from datetime import datetime, timedelta

path_data = '../data/asotr/'
fname_cmd_flight = '../data/cmd_asotr/all_flight_cmd_asotr.csv'
fname_cmd_temp = '../data/cmd_asotr/flight_cmd_temp.csv'
fname_cmd_human = '../data/cmd_asotr/cmd_human.csv'
timeformat = '%d.%m.%Y %H:%M:%S' 
prev_days = 25

## get flight commands file (generated by mvn_log_viewer) 
## Translate to human-readeble format and take temperatures from flight commands file
## save in cmd_human
cmd_list, temperature_list = asotr.get_cmd_data(fname_cmd_flight)
with open(fname_cmd_human, 'w') as file:
    for elem in cmd_list:
        file.write(f'{elem}\n')

## temperatures from flight commands file save to file flight_cmd_temp
with open(fname_cmd_temp, 'w') as file:
    file.write(f'timestamp_sec;timestamp;asotr_kit;ch1;ch2;ch3;ch4;ch5;ch6\r\n')
    for elem in temperature_list:
        file.write(f'{elem}\n')

## insert temperatures from flight commands file to main asotr temperatures data files
df_asotr_ = asotr.insert_temp_data_from_flight_cmd(fname_cmd_temp, path_data)

end_date = ''
for i, data in enumerate(df_asotr_):
    end_date = data['timestamp'].iloc[len(data) - 1][0:18]
    data.to_csv(f'{path_data}asotr0{i+1}_data_T.csv', index=False, sep=';', 
            encoding='utf-8-sig', decimal='.')

delta_date = datetime.strptime(end_date, timeformat) - timedelta(days=prev_days)
start_date = delta_date.strftime(timeformat)

## form timestamp file where minimum of temperatures registered 
for kit in range(1,3):
    asotr_kit = f'0{kit}'
    
    _, data_dict = asotr.get_data(path_data, asotr_kit, start_date, end_date, 'minutes')

    min_temp_ch = []
    for channel in range(1,7):
        ch = f'ch{channel}'
        data1 = data_dict['temp'][ch]
        time1 = data_dict['time_temp']

        periods_t, periods, _ = asotr.find_periods(time1, data1, shift_flag=False, peaks='min')

        min_temp_period = []
        for elem in periods_t:
            min_temp_period.append(elem.iloc[0].strftime('%d.%m.%Y %H:%M:%S.%f')[:-3])
        
        min_temp_ch.append(min_temp_period)

    fname = f'{path_data}asotr{asotr_kit}_min_T.csv'

    df = pd.DataFrame(min_temp_ch).transpose()
    df.to_csv(fname, header=False, index=False, sep=';', 
            encoding='utf-8-sig', decimal='.')
    df1 = pd.read_csv(fname, sep=';', 
            names=['ch1','ch2','ch3','ch4','ch5','ch6'])
    df1.to_csv(fname, index=False, sep=';', 
            encoding='utf-8-sig', decimal='.')


 







