from directory import createFolder, ROOT_DIR
from EEG import EEG
from PPG import PPG
import sys
import json
import warnings
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
import os
import datetime
import traceback
warnings.filterwarnings('ignore')
# filename
# device

def viewer_html_save(df, ch="ppg", color='salmon', RESULT_DIR='', current_time=''):
    # Create a scatter plot
    fig = px.line(df, x='time', y=ch)

    fig.update_traces(line=dict(color=color, width=3))

    if ch != "ppg":
        fig.update_layout(yaxis_range=[-100, 100])
    fig.update_layout(
            xaxis={'showgrid': True, 'zeroline': True, 'showline': False, 'showticklabels': True},
            yaxis={'showgrid': True, 'zeroline': True, 'showline': False, 'showticklabels': True},)
    fig.update_layout(title_text="Ch: "+ch.upper())
    fig.update_xaxes(rangeslider_visible=True)
    fig.write_html(os.path.join(RESULT_DIR, ch+"_"+current_time+".html"))
    return os.path.join(RESULT_DIR, ch+"_"+current_time+".html")



if __name__ == "__main__":
    file = sys.argv[1]      #뇌파 파일
    device = sys.argv[2]    #측정기기 laxtha, soso
    RESULT_DIR = sys.argv[3] # RESULT_DIR
    current_time = str(round(datetime.datetime.utcnow().timestamp() * 1000))

    # RESULT_DIR = RESULT_DIR.replace('/var/www/html/bwave/', '')

    print("file", file, ", device", device, ",\nRESULT_DIR: ", RESULT_DIR)


    html_dir = {'eeg1': '', 'eeg2': '', 'ppg': ''}

    eeg = EEG(file, RESULT_DIR, device=device)
    try:
        eeg.load_file(tmax=float("inf"))
        ch1_df, ch2_df = eeg.viewr_preprocess()
        eeg1_dir = viewer_html_save(ch1_df, ch="eeg1", color='firebrick', RESULT_DIR=RESULT_DIR, current_time=current_time)
        eeg2_dir = viewer_html_save(ch2_df, ch="eeg2", color='navy', RESULT_DIR=RESULT_DIR, current_time=current_time)

        html_dir['eeg1'] = eeg1_dir.replace('/var/www/html/bwave/', '')
        html_dir['eeg2'] = eeg2_dir.replace('/var/www/html/bwave/', '')
    except Exception as e: # EEG PROCESS ERROR 나오면 PPG만 레포트 출력하도록 CODE=-2005반환
        print("EEG DATA PROCESS ERROR\nerror:", traceback.format_exc())

    # eeg_json_val  = json.dumps(eeg.viewer_data)
    # print(eeg_json_val)

    ppg = PPG(file, RESULT_DIR, device=device)
    try:
        ppg.load_file()
        ppg_df = ppg.viewr_preprocess()
        ppg_dir = viewer_html_save(ppg_df, ch="ppg", color='mediumseagreen', RESULT_DIR=RESULT_DIR, current_time=current_time)

        html_dir['ppg'] = ppg_dir.replace('/var/www/html/bwave/', '')
    except Exception as e: # PPG PROCESS ERROR 나오면 EEG만 레포트 출력하도록 CODE=-2006반환
        print("PPG DATA PROCESS ERROR\nerror:", traceback.format_exc())


    json_val  = json.dumps(html_dir)
    print(json_val)
    # sys.exit()
