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

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

asotr_kit = 1
fname = f'../../python_cyclo/data/asotr0{asotr_kit}_data_T.csv' 
dateparse = lambda x: datetime.strptime(x, "%d.%m.%Y %H:%M:%S.%f")
data = pd.read_csv(fname, sep=';', parse_dates=['timestamp'], date_parser=dateparse)

# date = '20.03.2025'
# period = '1 мин'
# time_begin_orig = date + ' 17:10:11' 
# time_begin1 = date + ' 18:10:17'
# time_begin2 = date + ' 19:10:23'
# step_begin = time_begin2
# duration = 3600
# accuracy = 'seconds'
# name_fig = 'step_response_KDI_20242003.png'

# date = '21.03.2025'
# period = '1 мин'
# time_begin_orig = date + ' 14:00:11' 
# time_begin1 = date + ' 15:00:16'
# time_begin2 = date + ' 16:00:16'
# step_begin = time_begin2
# duration = 3600
# accuracy = 'seconds'
# name_fig = 'step_response_KDI_20242103.png'

# date = '24.03.2025'
# period = '1 сек'
# time_begin_orig = date + ' 19:45:11' 
# time_begin1 = date + ' 20:45:13'
# time_begin2 = date + ' 21:45:17'
# step_begin = time_begin2
# duration = 3600
# accuracy = 'seconds'
# name_fig = 'step_response_KDI_20242403.png'


# interp = {'method': 'polynomial', 'order': 2}
# thermocycle_info = {'date': '24.03.2025', 'time_begin': ['20:45:00', '21:45:11'], 
#         'duration_sec': 60*60, 'type': 'step'}
# cut_step_resp = {'time_step_begin': '21:45:11', 'step_duration': 60*60,
#         'orig_time_step_begin': '19:45:11', 'orig_step_duration': 25*60}
# data_info = {'data': data, 'device': 'KDI', 'channel': 'ch1', 'period': '1 мин', 
#         'find_accuracy': 'seconds'}
# name = f'{thermocycle_info["type"]}_response_diff_{data_info["device"]}_{thermocycle_info["date"].replace(".","")}'
# plot_info = {'title': 'Реакция на ступенчатое воздействие', 
#         'ox_dtime_format': "%H:%M:%S", 'legend_pos': ['upper left', 'lower left'],
#         'name_fig': f'{name}.png', 'font': 10}


interp = {'method': 'polynomial', 'order': 2}
thermocycle_info = {'date': '01.04.2025', 
        'time_begin': ['01.04.2025 16:27:00', '01.04.2025 18:00:00'], 
        'duration_sec': 92*60, 'type': 'step'}
cut_step_resp = {'time_step_begin': '01.04.2025 18:53:21', 'step_duration': 24*60,
        'orig_time_step_begin': '01.04.2025 15:22:10', 'orig_step_duration': 24*60}
data_info = {'data': data, 'channel': 'ch1', 'period': '1 мин', 
        'find_accuracy': 'seconds'}
plot_info = {'title': 'Реакция на ступенч. воздейств.', 
        'ox_dtime_format': "%H:%M:%S", 'legend_pos': ['lower right', 'lower left'],
        'name_fig': '../plots/response/step_response_diff_KDI_20240401.png', 'font': 10}

step_resp_cut, _, _ = asotr.get_step_response_diff(data_info['data'], thermocycle_info, 
        channel=data_info['channel'], interp=interp, accuracy=data_info['find_accuracy'], 
        cut_step_resp=cut_step_resp)

tstamp_orig_begin = cut_step_resp['orig_time_step_begin']

_, interp_step_resp = asotr.cut_norm_data(data_info['data'], tstamp_orig_begin, 
        cut_step_resp['orig_step_duration'], channel='ch1', interp=interp, 
        accuracy=data_info['find_accuracy'])

max_ = min(len(interp_step_resp), len(step_resp_cut))

step_resp_cut.to_csv(f'../data/asotr/response/asotr0{asotr_kit}_{thermocycle_info["type"]}_{thermocycle_info["date"].replace(".","")}.csv', index=False, sep=';', encoding='utf-8-sig', decimal='.')

title = f'{plot_info["title"]}, канал {data_info["channel"][2]} АСОТР КДИ СПИН-X1-МВН, период опроса {data_info["period"]} ({thermocycle_info["date"]})'

fig = plt.figure(figsize=(6, 6), dpi=200)
fig.suptitle(title, fontsize=plot_info['font'])
ax1 = fig.add_subplot(1,1,1)

ax1.plot(step_resp_cut['timestamp'].iloc[0:max_], step_resp_cut['temp'].iloc[0:max_], '--',
        label='реакция на ступенчатое воздействие с термоциклом')
ax1.plot(step_resp_cut['timestamp'].iloc[0:max_], interp_step_resp['temp'].iloc[0:max_],
        label='реакция на ступенчатое воздействие')

date_formatter = dates.DateFormatter(plot_info['ox_dtime_format'])
ax1.xaxis.set_major_formatter(date_formatter)
ax1.legend(loc=plot_info["legend_pos"][0], fontsize=plot_info['font'])
ax1.grid(True)
ax1.tick_params(axis='both', width=1, labelsize=plot_info['font'])
ax1.set_ylabel(r'$T_{норм}$, $^\circ$C', fontsize=plot_info['font'])
ax1.set_xlabel('Время', fontsize=plot_info['font'])

plt.tight_layout()
fig.savefig(plot_info["name_fig"])
plt.show()
