# -*- coding: utf-8 -*-
""" Router """

from urllib.parse import urlparse, parse_qs
import dash
from dash import dcc
from dash import html
from dash.dependencies import Output
from dash.dependencies import Input
from map_handler import VARS 
from map_handler import MODELS
from map_handler import DEBUG
from map_handler import ALIASES
from map_handler import ROUTE_DEFAULTS
from utils import render404

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 logging

#-------------------- ADD ROUTING FUNCTIONS ----------------------
def get_input_aliases(route_selections):
    """ Change user inputs into internal variables"""
    for key, value in route_selections.items():
        #preserve the list of models by only changing the individual model name
        if key == 'model':
            route_selections[key] = ['median' if x=='multi-model' else x for x in route_selections[key]]
        elif value[0] in ALIASES:
            route_selections[key] = [ALIASES[value[0]]]
    return route_selections

def eval_section_query(queries):
    """pull SECTION var from url query and assign value to appropriate option"""
    
    if 'section' in queries:
        if queries['tab'] == ['forecast-tab']:
            queries['for_option'] = queries['section']
        elif queries['tab'] == ['evaluation-tab']:
            queries['eval_option'] = queries['section']
        elif queries['tab'] == ['observations-tab']:
            queries['obs_option'] = queries['section']

    return queries   

def get_url_queries(url, route_defaults=ROUTE_DEFAULTS):
    """ pull all of the keyword arguments from url and update ROUTE_DEFAULTS dict as necessary""" 
    parsed_url = urlparse(url, scheme='http', allow_fragments=False)
    queries = parse_qs(parsed_url[4])
    route_selections = route_defaults.copy()
    route_selections.update(queries)
    route_selections = get_input_aliases(route_selections)
    route_selections = eval_section_query(route_selections)
    return route_selections

@dash.callback(
    Output('app-sidebar', 'children'),
    [Input('app-tabs', 'value')],
    prevent_initial_call=True
)
def render_sidebar(tab='forecast-tab', route_selections=ROUTE_DEFAULTS):
    """ Function rendering requested tab """
    tabs = {
        'forecast-tab' : sidebar_forecast(VARS,
                                          route_selections['var'][0],
                                          MODELS,
                                          route_selections['model'],
                                          window=route_selections['for_option'][0],
                                          country=route_selections['country'][0]),
        'evaluation-tab' :
        sidebar_evaluation(route_selections['eval_option'][0]),
        'observations-tab' :
        sidebar_observations(route_selections['obs_option'][0]),
    }
    return tabs[tab]

@dash.callback(
        Output("content", "children"),
        Input("url", "href"),
        )
def router(url):
    """ Get url search queries and build layout for app"""
    
    route_selections = get_url_queries(url)
    logging.info('===== route_selections %s', route_selections)
    
    try:
        children = [
                html.Div(
                    id='app-sidebar',
                    children=render_sidebar(route_selections['tab'][0],
                                            route_selections), 
                    className='sidebar'
                    ),
                dcc.Tabs(id='app-tabs', value=route_selections['tab'][0] , children=[
                    tab_forecast(window=route_selections['for_option'][0], end_date=route_selections['date'][0]),
                    tab_evaluation(route_selections['eval_option'][0]), #nrt or scores
                    tab_observations(route_selections['obs_option'][0]),#rgb or visibility
                    go_fullscreen(),
                    ]),
                ]
    except Exception as err: # This handles when user inputs incorrect URL params
        logging.error("ERROR 404 %s", str(err))
        children = render404()
        
    return children
