import sys
import statistics
from importlib import reload
sys.path.append('./')
import asotr
reload(asotr)
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib import dates
from datetime import timedelta

path = '../data/asotr/'
channel = 'ch1'
asotr_kit = '01'
start_date = '25.04.2025 00:00:00'
end_date = '25.04.2025 08:00:00'
forecast_days = 20


timeformat = '%d.%m.%Y %H:%M:%S' 
num_peaks_forecast = forecast_days * 20
shift = True 

try:
    raw_data, data_dict = asotr.get_data(path, asotr_kit, start_date, end_date, 'minutes')
except Exception as e:
    sys.exit()

data1 = data_dict['temp'][channel]
time1 = data_dict['time_temp']

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

peaks_forecast = asotr.get_peak_temp_forecast(time1.iloc[peaks[0]], num_peaks_forecast)

with open('../data/asotr/peaks_forecast.txt', 'w') as file:
    for elem in peaks_forecast:
        file.write(f'{str(elem)}\n')

delta_sec = []
for idx, elem in enumerate(peaks):
    if idx > 0:
        delta = time1.iloc[elem] - peaks_forecast[idx-1]
        # print(delta)
        delta_sec.append(delta.total_seconds())

delta_self_sec = []
delta_self_sec1 = []
for idx, elem in enumerate(periods_t):
    delta1 = elem.iloc[len(elem)-1] - elem.iloc[0]
    delta_self_sec.append(delta1.total_seconds())

for idx, elem in enumerate(delta_self_sec):
    if idx > 0:
        delta_self_sec1.append(delta_self_sec[idx] - delta_self_sec[idx - 1])

# print(delta_self_sec)
print(statistics.median(delta_self_sec))

ox_dtime_format = "%d.%m.%Y %H:%M"
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(8, 6))

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

ax1.plot(time1, data1)
for elem in peaks:
    ax1.axvline(x = time1.iloc[elem], color='r', linewidth=0.5)
    
ax1.set_title(f'температура на орбите: АСОТР{asotr_kit}, канал {channel[2]}')

ax2.set_title('Разница по времени между временем i-го пика и i-м предсказанием пика')
ax2.set_ylabel(r'$\Delta$$t_{peak}$ = $timePeak_i$ - $timeForecast_i$, сек')
ax2.plot(delta_sec)

ax3.set_title('Разница по времени между первым и последующим периодами')
ax3.set_ylabel(r'$\Delta$$t_{period}$ = $period_i$ - $period_0$, сек')
ax3.plot(delta_self_sec1)

ax1.set_ylabel('Температура, град.')

ax1.grid(True)
ax2.grid(True)
ax3.grid(True)
plt.show()
