
import numpy as np
import obspy.signal.filter as flt
# from scipy.signal import detrend as dtrnd
from Additional_Funs.classicstalta_fun import run_classicstalta
from Additional_Funs.trigger_fun import trigger_veq02
import datetime
from datetime import datetime, timedelta
import pandas as pd
import csv

def detection_veq02(input_detection):

    w_final =  input_detection[0]
    cdat = input_detection[1]
    fs = input_detection[2]
    station = input_detection[3]
    t_buf = input_detection[4]
    t_sta = input_detection[5]
    t_lta = input_detection[6]
    tsl_smooth = input_detection[7]
    thresh_on = input_detection[8]
    thresh_off = input_detection[9]
    tenv_smooth = input_detection[10]
    env_off = input_detection[11]
    start_date = input_detection[12]
    init_hour = input_detection[13]
    final_hour = input_detection[14]
    output_csv = input_detection[15]

    # start_w = start_date - 60


    # Detrend and Bandpass Filter
    # data_detrend = dtrnd(w_final, type='linear')

    data_filtered = flt.bandpass(w_final, freqmin=1.0, freqmax=15.0, df=fs, corners=2, zerophase=True)
    data_final = data_filtered.copy()
    buffer_l = t_buf * fs
    buffer_r = buffer_l
    t_array = np.arange(0, (len(data_final)/fs), 1/fs)

    # STA/LTA Parameters
    sliding = 1
    num_el = int(((len(data_final) / sliding) - ((t_sta + t_lta) * sliding * fs) + 1))

    # Calculate Envelope
    analytic_data_final = flt.envelope(data_final)
    env_data_final = np.abs(analytic_data_final)
    env_data_final  = pd.Series(env_data_final)
    smooth_env_data_fin = env_data_final.rolling(window=int(tenv_smooth * fs), min_periods=1, center=True).median()
    smooth_env_data_pick = smooth_env_data_fin[int(t_lta * fs - 1):int(t_lta * fs + num_el - 1)]
    stalta_ser = run_classicstalta(abs(data_final), int((t_sta * fs)), int((t_lta * fs)))

    # Extract Trigger-On and Trigger-Off
    trig_on, valu_on, trig_off, valu_off, idx_on = trigger_veq02(smooth_env_data_pick, stalta_ser, thresh_on,
                                                                 thresh_off, fs, tsl_smooth, env_off)

    # For Plotting
    idx_ratio = np.arange(0, len(data_final), sliding)
    t_ratio = t_array[idx_ratio]
    t_plot_rat = t_lta + t_ratio[0:(len(t_ratio) - (len(idx_ratio) - len(stalta_ser)))]

    # Extract n hour detection

    t_nhour = t_array[int(buffer_l):(len(cdat) + int(buffer_r) - 1)]
    idx_detect = np.stack([trig_on, trig_off], 1)

    for k in range(len(trig_on)):
        if t_plot_rat[trig_on[k]] < t_nhour[0] or t_plot_rat[trig_on[k]] > t_nhour[-1]:
            idx_detect[k, :] = np.array([-99999, -99999])
        elif t_plot_rat[trig_off[k]] > t_nhour[-1]:
            if idx_detect[k, 0] == -99999:
                idx_detect[k, 1] = -99999
            else:
                idx_detect[k, 1] = idx_detect[k, 1]

    rmv_idx = np.where(idx_detect[:, 0] == -99999)
    idx_detect = np.delete(idx_detect, rmv_idx, axis=0)


    # Exporting to csv
    csv_title = 'Catalogue_' + station + '_' + str(t_sta) + '_' + str(t_lta) + '_' + str(start_date.year)  + \
                str(start_date.month) +  str(start_date.day) + '_' + str(init_hour) + '_' + str(final_hour) + \
                '_' + 'hour.csv'

    path_to_csv = output_csv + csv_title

    init_time_date = start_date
    init_time_pick = datetime(init_time_date.year, init_time_date.month, init_time_date.day,
                              init_time_date.hour + init_hour, init_time_date.minute,
                              init_time_date.second, init_time_date.microsecond)

    delta_t_on = (t_plot_rat[idx_detect[:, 0]] - t_array[int(buffer_l)]) / 3600
    time_events_on = [init_time_pick + timedelta(hours=delta_ton) for delta_ton in delta_t_on]
    delta_t_off = (t_plot_rat[idx_detect[:, 1]] - t_array[int(buffer_l)]) / 3600
    time_events_off = [init_time_pick + timedelta(hours=delta_toff) for delta_toff in delta_t_off]

    event_on_str_dmy = [time_event_list.strftime("%d%m%Y") for time_event_list in time_events_on]
    event_on_str_hms = [time_event_list.strftime("%H%M%S") for time_event_list in time_events_on]

    event_id = []
    event_dur = []

    for jj in range(len(time_events_on)):
        event_id.append('EQ' + event_on_str_dmy[jj] + 'T' + event_on_str_hms[jj])
        event_dur.append(time_events_off[jj] - time_events_on[jj])

    event_dur_sec = np.zeros(len(time_events_on))

    for jj in range(len(time_events_on)):
        event_dur_sec[jj] = event_dur[jj].seconds + event_dur[jj].microseconds / 1E6

    # i_time_p_str = init_time_pick.strftime("%d %b %Y_%H_%M_%S")

    header_csv = ['Event_ID', 'time_events_on', 'time_events_off', 'event_dur_sec', 'detect_seq']

    rows = len(time_events_on)
    cols = 5
    csv_data = [[None for _ in range(cols)] for _ in range(rows)]

    for kk in range(len(time_events_on)):
        csv_data[kk][:] = [event_id[kk], time_events_on[kk], time_events_off[kk], event_dur_sec[kk], kk+1]

    with open(path_to_csv, 'w', encoding='UTF8', newline='') as f:
        writer = csv.writer(f)

        # write the header
        writer.writerow(header_csv)

        # write multiple rows
        writer.writerows(csv_data)

    return t_array, data_final, t_plot_rat, idx_detect, stalta_ser, smooth_env_data_pick

