""" TAB OBSERVATIONS """
import dash
from dash.dependencies import Output
from dash.dependencies import Input
from dash.dependencies import State
from dash.dependencies import ALL
from dash.exceptions import PreventUpdate
from data_handler import DEBUG
from data_handler import START_DATE, END_DATE
from data_handler import SATELLITE_IMAGE_SRC

from tabs.observations import tab_observations

from datetime import datetime as dt
import math
import logging

from data_handler import cache, cache_timeout 

@dash.callback(
    [Output('observations-tab', 'children'),
     Output('rgb', 'style'),
     Output('visibility', 'style'),
     Output('variable-dropdown-observation', 'value')],
    [Input('rgb', 'n_clicks'),
     Input('visibility', 'n_clicks')],
    prevent_initial_call=True
)
def render_observations_tab(rgb_button, vis_button):
    """ Function rendering requested tab """
    ctx = dash.callback_context

    bold = { 'font-weight': 'bold' }
    norm = { 'font-weight': 'normal' }

    logging.debug('rgb and vis buttons %s %s', rgb_button, vis_button)

    if ctx.triggered:
        logging.debug('render_obs_tab ctx %s', ctx.triggered[0]["prop_id"].split("."))
        button_id = ctx.triggered[0]["prop_id"].split(".")[0]

        if button_id == "rgb" and rgb_button:
            return tab_observations('rgb', START_DATE, END_DATE), bold, norm, button_id
#             elif button_id == "aod" and aod_button:
#                 return tab_observations('aod'), norm, bold, norm, button_id
        elif button_id == "visibility" and vis_button:
            return tab_observations('visibility', START_DATE, END_DATE), norm, bold, button_id

        return dash.no_update, bold, norm, 'rgb'
    raise PreventUpdate

@dash.callback(
[Output('rgb-image', 'src'),
 Output('btn-fulldisc', 'active'),
 Output('btn-middleeast', 'active')],
[Input('btn-fulldisc', 'n_clicks'),
 Input('btn-middleeast', 'n_clicks'),
 Input('obs-date-picker', 'date'),
 Input('obs-slider-graph', 'value')],
[State('btn-fulldisc', 'active'),
 State('btn-middleeast', 'active')],
 prevent_initial_call=True
)
@cache.memoize(timeout=cache_timeout)
def update_image_src(btn_fulldisc, btn_middleeast, date, tstep, btn_fulldisc_active, btn_middleeast_active):

    logging.debug('BUTTONS %s %s %s %s', date, tstep, btn_fulldisc_active, btn_middleeast_active)
    ctx = dash.callback_context
    if ctx.triggered:
        button_id = ctx.triggered[0]["prop_id"].split(".")[0]
    else:
        button_id = None
    if button_id not in ('btn-fulldisc', 'btn-middleeast'):
        if btn_middleeast_active:
            button_id = 'btn-middleeast'
        elif btn_fulldisc_active:
            button_id = 'btn-fulldisc'

    logging.debug('BUTTONS %s', button_id)

    if button_id == 'btn-middleeast':
        path_tpl = SATELLITE_IMAGE_SRC['middle_east']
        btn_fulldisc_active = False
        btn_middleeast_active = True
    elif button_id == 'btn-fulldisc':
        path_tpl = SATELLITE_IMAGE_SRC['fulldisc']
        btn_fulldisc_active = True
        btn_middleeast_active = False

    try:
        date = dt.strptime(date, '%Y-%m-%d').strftime('%Y%m%d')
    except:
        pass
    path = path_tpl.format(date=date, tstep=tstep)
    logging.debug('...... %s', path)
    return dash.get_asset_url(path), btn_fulldisc_active, btn_middleeast_active


# start/stop animation
@dash.callback(
    [Output('obs-slider-interval', 'disabled'),
     Output('obs-slider-interval', 'n_intervals'),
     Output('btn-obs-play', 'className')],
    Input('btn-obs-play', 'n_clicks'),
    [State('obs-slider-interval', 'disabled'),
     State('obs-slider-graph', 'value')],
    prevent_initial_call=True
)
@cache.memoize(timeout=cache_timeout)
def start_stop_obs_autoslider(n_play, disabled, value):
    """ Play/Pause map animation """
    ctx = dash.callback_context
    logging.debug("VALUE %s", value)
    if not value:
        value = 0
    if ctx.triggered:
        button_id = ctx.triggered[0]["prop_id"].split(".")[0]
        if button_id == 'btn-obs-play' and disabled:
            return not disabled, int(value), 'fa fa-pause text-center'
        elif button_id == 'btn-obs-play' and not disabled:
            return not disabled, int(value), 'fa fa-play text-center'

    raise PreventUpdate

@dash.callback(
    Output('obs-slider-graph', 'value'),
    [Input('obs-slider-interval', 'n_intervals')],
    prevent_initial_call=True
    )
@cache.memoize(timeout=cache_timeout)
def update_obs_slider(n):
    """ Update slider value according to the number of intervals """
    logging.debug('SERVER: updating slider-graph %s', str(n))
    if not n:
        return 0
    if n >= 24:
        tstep = int(round(24*math.modf(n/24)[0], 0))
    else:
        tstep = int(n)
    logging.debug('SERVER: updating slider-graph %s', str(tstep))
    return tstep

@dash.callback(
    Output('obs-vis-graph', 'children'),
    [Input('obs-vis-date-picker', 'date'),
     Input('obs-vis-slider-graph', 'value')],
    [State({'index': ALL, 'tag': 'obs-vis-map'}, 'zoom'),
     State({'index': ALL, 'tag': 'obs-vis-map'}, 'center')],
    # prevent_initial_call=False
)
@cache.memoize(timeout=cache_timeout)
def update_vis_figure(date, tstep, zoom, center):
    from tools import get_vis_figure
    from tools import get_models_figure
    logging.debug("************* %s %s %s %s", date, tstep, zoom, center)
    if date is not None:
        date = date.split(' ')[0]
        try:
            date = dt.strptime(
                date, "%Y-%m-%d").strftime("%Y%m%d")
        except:
            pass
    else:
        date = END_DATE

    if zoom:
        zoom = zoom[0]
    else:
        zoom = None

    if center:
        center = center[0]
    else:
        center = None

    # view = list(STYLES.keys())[view.index(True)]
    logging.debug('SERVER: VIS callback date %s tstep %s', date, tstep)
    layers = get_vis_figure(tstep=tstep, selected_date=date)
    fig = get_models_figure(model=None, var=None, layer=layers, zoom=zoom, center=center, tag='obs-vis')
    return fig
