"""Example of using hangups to receive chat messages.
Uses the high-level hangups API.
"""

import hangups
import os
import shutil

import analysis.querydb as qdb
import pandas as pd
from datetime import datetime, timedelta
import fb.xyzrealtimeplot as xyz

import analysis.analysislib as lib
import analysis.rainfall.rainfall as rain
import analysis.surficial.markeralerts as marker
import analysis.subsurface.plotterlib as plotter
import analysis.subsurface.proc as proc
import analysis.subsurface.rtwindow as rtw

import gsm.alertmessaging as amsg
import gsm.smsparser2.smsclass as smsclass

import ops.lib.lib as ops_lib

import volatile.memory as mem
import dynadb.db as db


def check_event(site_id):
    return

def subsurface_plot():
    
    data = proc.proc_data(tsm_props, window, sc, realtime=True, comp_vel=plotvel, analysis=False)
    
    if print_disp_vel == 'y':
        tilt = data.tilt.reset_index()
        accel = data.accel_data.reset_index()
        df = pd.merge(tilt, accel, on=['ts', 'node_id', 'tsm_name']).sort_values(['ts', 'node_id'])
        df.to_csv('{}_{}-{}.csv'.format(tsm_props.tsm_name, window.start.strftime('%Y%m%d%H%M'), window.end.strftime('%Y%m%d%H%M')), index=False)

#    data, tsm_props, window, sc, plotvel=True, show_part_legend = False,
#             realtime=True, plot_inc=True, three_day_window=True,
#             mirror_xz=False, mirror_xy=False, zeroed_colpos=False, plotdispvel=True

    plotter.main(data, tsm_props, window, sc, plotvel=plotvel,
                 show_part_legend = show_part_legend, realtime=True,
                 plot_inc=False, three_day_window=three_day_window,
                 mirror_xz=mirror_xz, mirror_xy=mirror_xy)

def data_availability(alert):    
    site_id = alert.site_id
    site = alert.site_code
    ts = alert.ts_last_retrigger
    source_id = alert.source_id
    alert_id = alert.stat_id
    
    OutputFP=  os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')) #os.path.dirname(os.path.realpath(__file__))+'/{} {}/'.format(site, ts.strftime("%Y-%m-%d %H%M"))
    OutputFP += '/node_alert_hangouts/' + '{} {} {}/'.format(alert_id, site, ts.strftime("%Y-%m-%d %H%M")) 
    OutputFP=OutputFP.replace("\\", "/")

    #### Open config files
    sc = mem.get('server_config')
    output_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))
    
    if not os.path.exists(OutputFP):
        os.makedirs(OutputFP)

    
    if source_id ==1:

        
        ts_before=ts.round('4H')-timedelta(hours=4)
        
        queryalert="""SELECT na_id,ts,t.tsm_id,tsm_name,node_id,disp_alert,vel_alert 
                    FROM node_alerts
                    inner join tsm_sensors as t
                    on t.tsm_id=node_alerts.tsm_id
                    where site_id={} and (ts between '{}' and '{}')
    
                    order by tsm_name, node_id, ts desc""".format(alert.site_id,ts_before,ts)
        dfalert=db.df_read(queryalert,connection = "analysis").groupby(['tsm_id','node_id']).first().reset_index()
        print("ok")
#        plot colpos & disp vel
        tsm_props = qdb.get_tsm_list(dfalert.tsm_name[0])[0]
        window, sc = rtw.get_window(ts)
        
        data = proc.proc_data(tsm_props, window, sc)
        plotter.main(data, tsm_props, window, sc, plot_inc=False)
        
        plot_path_sensor = output_path+sc['fileio']['realtime_path']
        
        for img in os.listdir(plot_path_sensor):
            if os.path.exists('{}/{}'.format(OutputFP, img)):
                os.remove('{}/{}'.format(OutputFP, img))
            shutil.move("{}/{}".format(plot_path_sensor,img), OutputFP)
        
#        plot node data
        for i in dfalert.index:
            print (dfalert.tsm_name[i],dfalert.node_id[i],dfalert.ts[i])
            
            xyz.xyzplot(dfalert.tsm_id[i],dfalert.node_id[i],dfalert.ts[i],OutputFP)
            
    elif source_id == 3:
        rain.main(site_code = site, end=ts, write_to_db = False, print_plot = True)
        

        
        plot_path_rain = output_path+sc['fileio']['rainfall_path']
        
        for img in os.listdir(plot_path_rain):    
            shutil.move("{}/{}".format(plot_path_rain,img), OutputFP)
            
    elif source_id ==2:
#        print("marker")
#        query_alert = ("SELECT marker_id FROM marker_alerts "
#                       "where ts = '{}' and alert_level >0".format(ts))
#        dfalert=db.df_read(query_alert,connection = "analysis")
        
        
#        for m_id in dfalert.marker_id:
        marker.generate_surficial_alert(site_id=site_id, ts = ts)#, marker_id=m_id)
        
        
        plot_path_meas = output_path+sc['fileio']['surficial_meas_path']
        plot_path_trend = output_path+sc['fileio']['surficial_trending_path']
        
        for img in os.listdir(plot_path_meas):    
            shutil.move("{}/{}".format(plot_path_meas,img), OutputFP)
        
        for img in os.listdir(plot_path_trend):    
            shutil.move("{}/{}".format(plot_path_trend,img), OutputFP)
    return OutputFP

def send_plots(site_req, ts):
    site_code = site_req['site_code'].values[0]
    c_id = site_req['c_id'].values[0]
    
    for source_id in site_req.source_id:
        data_availability()
        

#    message = "Checking data availability for {} {} ...".format(site_code.upper(), ts)        
#    message = "Generating plots for {} {} ...".format(site_code.upper(), ts)
#    cmd = "{} {}/send_message.py --conversation-id {} --message-text '{}'".format(python_path,file_path,c_id,message)
#    os.system(cmd)
    
#    for source_id in site_req.source_id:
   
    for a in os.listdir(OutputFP):
        print (a)
        cmd = "{} {}/upload_image.py --conversation-id {} --image '{}'".format(python_path,file_path,c_id,OutputFP+a)
        os.system(cmd)

def scheduled_requests():
    ts = lib.round_data_ts(datetime.now())
    
    query = "SELECT * FROM olivia_plot_requests WHERE is_active = 1"
    req_df = db.df_read(query,connection = "analysis")
    req_df = req_df.loc[(ts.hour+4) % req_df.hrs_interval == 0, :]
    
    if len(req_df) != 0:
        req_df = pd.merge(req_df, mem.get('df_sites'), on='site_id')
        
        releases = ops_lib.release_sched(start=ts-timedelta(hours=23.5), end=ts)
        with_event = releases.loc[releases.event == 1, ['site_code', 'data_ts']]
        
        req_df = req_df.loc[req_df.apply(lambda row: len(with_event.loc[(with_event.site_code == row.site_code) & (with_event.data_ts >= ts-timedelta(hours=row.hrs_interval))]) != 0, axis=1), :]
        
        site_req = req_df.groupby('site_id', as_index=False)
        site_req.apply(send_plots, ts=ts)
    
    return

if __name__ == '__main__':
    query = "SELECT link from olivia_link where link_id = 3"
    python_path = db.read(query, connection = "gsm_pi")[0][0]
    
    file_path = os.path.dirname(__file__)
    
    ts = pd.to_datetime('2022-03-10 20:15')
    ts = lib.round_data_ts(ts)
#    
#    run_example(receive_messages)