""" 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 datetime import datetime as dt
from datetime import timedelta
from urllib.parse import urlparse, parse_qs

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 data_handler import DATES
from data_handler import cache, cache_timeout 
from data_handler import ALIASES
from data_handler import ROUTE_DEFAULTS

from tabs.forecast import tab_forecast
from tabs.forecast import sidebar_forecast
from tabs.evaluation import tab_evaluation
from tabs.evaluation import sidebar_evaluation
from tabs.observations import tab_observations
from tabs.observations import sidebar_observations
from tabs.fullscreen import go_fullscreen 

import uuid
import socket

from router import *

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"

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.init_app(server)

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>
"""
if DEBUG: print('SERVER: start creating app layout')

#SET APP LAYOUT TO BE POPULATED
app.layout = html.Div([dcc.Location(id="url", refresh=False)], id="content")
    
if DEBUG: print('SERVER: stop creating app layout')

from tabs.forecast_callbacks import *
from tabs.evaluation_callbacks import *
from tabs.observations_callbacks import *

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