""" Dash Server """

#import gevent.monkey
#gevent.monkey.patch_all()

import dash
import dash_bootstrap_components as dbc
from dash import dcc
from dash import html
from dash.dependencies import Output
from dash.dependencies import Input
from dash.dependencies import State
from dash.dependencies import ALL
from dash.dependencies import MATCH
from dash.dependencies import ClientsideFunction
from dash.exceptions import PreventUpdate
import flask
from flask import g, make_response, request
from flask_caching import Cache
#from pyinstrument import Profiler
from pathlib import Path

from data_handler import DEFAULT_VAR
from data_handler import DEFAULT_MODEL
from data_handler import VARS 
from data_handler import MODELS
from data_handler import DEBUG

from tabs.forecast import tab_forecast
from tabs.forecast import sidebar_forecast
from tabs.forecast_callbacks import register_callbacks as fcst_callbacks
from tabs.evaluation import tab_evaluation
from tabs.evaluation import sidebar_evaluation
from tabs.evaluation_callbacks import register_callbacks as eval_callbacks
from tabs.observations import tab_observations
from tabs.observations import sidebar_observations
from tabs.observations_callbacks import register_callbacks as obs_callbacks
from tabs.fullscreen import go_fullscreen 

import uuid
import socket

HOSTNAME = socket.gethostbyname_ex(socket.gethostname())[0]

if HOSTNAME in ('bscesdust03.bsc.es', 'dust.hqads.aemet.es'):
    pathname = '/daily_dashboard/'
else:
    pathname = '/dashboard/'

TIMEOUT = 10

fontawesome = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css'
leaflet = "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.css"
# fontawesome = 'https://use.fontawesome.com/releases/v5.15.4/css/all.css'

srv = flask.Flask(__name__)
app = dash.Dash(__name__,
                external_scripts=['https://code.jquery.com/jquery-3.6.0.slim.min.js'],
                external_stylesheets=[dbc.themes.BOOTSTRAP,
                                      dbc.themes.GRID,
                                      fontawesome,
                                      leaflet
                                     ],
                url_base_pathname=pathname,
                server=srv,
                prevent_initial_callbacks=True
                )
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True
app.config.suppress_callback_exceptions = True
server = app.server

cache_dir = "/dev/shm/{}".format(str(uuid.uuid1()))
Path(cache_dir).mkdir(parents=True, exist_ok=True)

cache_config = {
    "DEBUG": True,
    "CACHE_TYPE": "FileSystemCache",
    "CACHE_DIR": cache_dir,
}

cache = Cache(server, config=cache_config)
cache_timeout = 86400

try:
    cache.clear()
except Exception as e:
    print('CACHE CLEAR ERROR:', str(e))
    pass


app.index_string = """
<!DOCTYPE html>
<html>
    <head>
        <script>
            L_PREFER_CANVAS=true;
            L_DISABLE_3D=true;
            L_SCROLL_WHEEL_ZOOM=false;

            HTMLCanvasElement.prototype.getContext = function(origFn) {
            return function(type, attribs) {
            attribs = attribs || {};
            attribs.preserveDrawingBuffer = true;
            return origFn.call(this, type, attribs);
             };
            }(HTMLCanvasElement.prototype.getContext);
        </script>
        <!-- Global site tag (gtag.js) - Google Analytics -->
        <!--
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-5V3R8V4021"></script>
        <script>
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', 'G-5V3R8V4021');
        </script>
        -->
        {%metas%}
        <title>{%title%}</title>
        {%favicon%}
        {%css%}
    </head>
    <body>
        {%app_entry%}
        <footer>
            {%config%}
            {%scripts%}
            {%renderer%}
        </footer>
    </body>
</html>
"""

#app.clientside_callback(
#    ClientsideFunction(
#        namespace='clientside',
#        function_name='update_url'
#    ),
#    Output('url', 'pathname'),
#    Input('app-tabs', 'value')
#)
#
@app.callback(
    Output('app-sidebar', 'children'),
    [Input('app-tabs', 'value')],
)
def render_sidebar(**kwargs):
    """ Function rendering requested tab """
    print('-----------render sidebar kwargs ', kwargs)
    tab = kwargs['tab']
    default_model = kwargs['default_model']
    tabs = {
        'forecast-tab' : [
            sidebar_forecast,
            (VARS, DEFAULT_VAR, MODELS, default_model)
            ],
        'evaluation-tab' : [
            sidebar_evaluation,
            None
            ],
        'observations-tab' : [
            sidebar_observations,
            None
            ],
        'fullscreen-tab' : [
            'Full'
            ]
    }

    if tabs[tab][0] is 'Full':
        return 
    elif tabs[tab][1] is None:
        return tabs[tab][0]()
    return tabs[tab][0](*tabs[tab][1])

app.layout = html.Div([
    dcc.Location(id="url", refresh=True)
], id="content")

def get_args(url):
    from urllib.parse import urlparse, parse_qs
    parsed_url = urlparse(url, scheme='http', allow_fragments=False)
    args = parse_qs(parsed_url[4])
    print('-------args----',args)
    return args

def get_tab(args):
    print('=========tab', args['tab'])
    tab = args['tab'][0]
    if tab =='evaluation':
        return 'evaluation-tab'
    elif tab =='observations':
        return 'observations-tab'
    elif tab =='forecast':
        return 'forecast-tab'
    return 'forecast-tab'

def get_obs_option(args):
    if 'visibility' in args: 
        obs_option = 'visibility' 
    else:
        obs_option='rgb'
    return obs_option

def get_eval_option(args):
    if 'scores' in args: 
        eval_option = 'scores' 
    else:
        eval_option='nrt'
    return eval_option

def get_forecast_models(args):
    if 'models' in args.keys():
        return args['models']
    return [DEFAULT_MODEL]

@app.callback(
    Output("content", "children"),
    Input("url", "href")
)
def router(url):
    args = get_args(url)
    tab = get_tab(args)
    eval_option = get_eval_option(args)
    obs_option = get_obs_option(args)
    models = get_forecast_models(args)

    children = [
        html.Div(
            id='app-sidebar',
            #children=sidebar_forecast(VARS, DEFAULT_VAR, MODELS, DEFAULT_MODEL),
            children=render_sidebar(tab=tab, default_model=models), 
            className='sidebar'
        ),
        dcc.Tabs(id='app-tabs', value=tab , children=[
            tab_forecast(),#models prob was
            tab_evaluation(eval_option), #nrt or scores
            tab_observations(obs_option),#rgb or visibility
            # go_fullscreen(pathname),
        ]),
    ]
    return children 

#if DEBUG: print('SERVER: start creating app layout')
#app.layout = html.Div(
#    children=[
#        html.Div(
#            id='app-sidebar',
#            #children=sidebar_forecast(VARS, DEFAULT_VAR, MODELS, DEFAULT_MODEL),
#            children=render_sidebar('evaluation-tab'), 
#            className='sidebar'
#        ),
#        dcc.Tabs(id='app-tabs', value='evaluation-tab', children=[
#            tab_forecast(),
#            tab_evaluation(),
#            tab_observations(),
#            # go_fullscreen(pathname),
#        ]),
#    ],
#    className="content",
#)
#
if DEBUG: print('SERVER: stop creating app layout')



fcst_callbacks(app, cache=cache, cache_timeout=cache_timeout)
eval_callbacks(app, cache=cache, cache_timeout=cache_timeout)
obs_callbacks(app, cache=cache, cache_timeout=cache_timeout)


if __name__ == '__main__':
    app.run_server(debug=True, # use_reloader=False,  # processes=4, threaded=False,
                   host='0.0.0.0', port=7777)
