from dash import dcc
import dash_bootstrap_components as dbc
from dash import html
from data_handler import DEBUG
from data_handler import DEFAULT_VAR
from data_handler import DEFAULT_MODEL
from data_handler import FREQ
from data_handler import VARS
from data_handler import MODELS
from data_handler import START_DATE, END_DATE
from data_handler import STYLES
from data_handler import DISCLAIMER_NO_FORECAST
# from tabs.forecast import layout_view
from utils import get_vis_edate

from datetime import datetime as dt
from datetime import timedelta

aod_end_date = '20210318'


layout_view = html.Div([
    html.Span(
        dbc.DropdownMenu(
            id='map-view-dropdown',
            label='VIEW',
            children=[
                dbc.DropdownMenuItem(
                    STYLES[style]['name'],
                    id=dict(
                        tag='vis-view-style',
                        index=style
                    ),
                    active=active
                )
                for style, active in zip(STYLES, [True if i == 'carto-positron'
                    else False for i in STYLES])
                ],
            direction="up",
        ),
    )])


def obs_time_slider(div='obs', start=0, end=23, step=1, start_date=START_DATE, end_date=END_DATE):
    # if DEBUG: print("------------\n", start, type(start), step, type(step), "------------\n")

    default_tstep = 0

    if div == 'obs-aod':
        edate = aod_end_date
    elif div == 'obs-vis':
        edate, default_tstep = get_vis_edate(end_date)
    else:
        edate = end_date

    # if DEBUG: print("------------\n", edate, default_tstep, "\n------------\n")
    date_picker = html.Span(
        dcc.DatePickerSingle(
            id='{}-date-picker'.format(div),
            min_date_allowed=dt.strptime(start_date, "%Y%m%d"),
            max_date_allowed=dt.strptime(edate, "%Y%m%d"),
            initial_visible_month=dt.strptime(edate, "%Y%m%d"),
            display_format='DD MMM YYYY',
            # date=(dt.strptime(edate, "%Y%m%d") - timedelta(days=1)).strftime("%Y%m%d"),
            date=dt.strptime(edate, "%Y%m%d").strftime("%Y%m%d"),
            clearable=True,
            placeholder='DD MON YYYY',
            reopen_calendar_on_clear=True,
        ),
        className="timesliderline",
    )

    play_button = html.Span(children=[
        html.Button(title='Play',
                    id='btn-{}-play'.format(div), n_clicks=0,
                    className='fa fa-play'),
        ],
        className="timesliderline anim-buttons",
    )
    
    if div == 'obs-vis':
        marks = {
            tstep: {'label': '{:02d}-{:02d}'.format(tstep, int(tstep+step))}
            # if tstep%2 == 0 else ''
            for tstep in range(start, end+1, step)
        }
        if DEBUG: print("MARKS", marks[list(marks.keys())[-1]])
        marks[list(marks.keys())[-1]]['style'] = {}
        marks[list(marks.keys())[-1]]['style']['left'] = ''
        marks[list(marks.keys())[-1]]['style']['right'] = '-32px'
    else:
        marks = {
            tstep: '{:d}'.format(tstep)
            # if tstep%2 == 0 else ''
            for tstep in range(start, end+1, step)
        }

    slider = html.Span(
        dcc.Slider(
            id='{}-slider-graph'.format(div),
            min=start, max=end, step=step, value=default_tstep, marks=marks
            # updatemode='drag',
        ),
        className="timesliderline",
    )

    if div == 'obs-vis':
        play_button = None

    return dbc.NavbarSimple([
        html.Div([
            date_picker,
            play_button,
            slider,
            ],
            className="timeslider"
            )],
        id='rgb-navbar',
        className='fixed-bottom navbar-timebar',
        fluid=True,
        expand='lg',
        dark=True,
        fixed='bottom',
        )

def tab_observations(window='rgb', start_date=START_DATE, end_date=END_DATE):
    """ """
    rgb_children = [
        html.Span(
            html.P(
                "EUMETSAT RGB"
                ),
            className="description-title"
        ),
        html.Span(
            html.P([
                html.B(
                    """
                    You can explore key observations that can be used to track dust events. 
                    """
                    ),
                """ All observations are kindly offered by Partners of the WMO Barcelona Dust Regional Center. RGB is a qualitative satellite product that indicates desert dust in the entire atmospheric column (represented by pink colour).""",
                ]
                ),
            className="description-body"
        ),
        html.Div([
            dbc.Button("HEMISPHERIC",
                id='btn-fulldisc',
                active=True,
            ),
            dbc.Button("MIDDLE EAST",
                id='btn-middleeast',
                active=False,
            ),
            ],
            id='rgb-buttons'
        ),
        html.Div([
            html.Img(
                id='rgb-image',
                src='./assets/eumetsat/FullDiscHD/archive/{date}/FRAME_OIS_RGB-dust-all_{date}{tstep:02d}00.gif'.format(date=end_date, tstep=0),
                alt='EUMETSAT RGB - NOT AVAILABLE',
                ),
            html.Div(
                obs_time_slider(div='obs', start_date=start_date, end_date=end_date),
                className="layout-dropdown",
            )],
            className='centered-image',
        ),
        html.Div(
            dcc.Interval(id='obs-slider-interval',
                interval=1000,
                n_intervals=0,
                disabled=True
        )),
    ]

    aod_children = [
        html.Span(
            html.P(
                "MetOffice AOD"
                ),
            className="description-title"
        ),
        html.Span(
            html.P([
                html.B("""You can explore key observations that can be used to track dust events. """),
                """All observations are kindly offered by Partners of the WMO Barcelona Dust Regional Center. AOD is a quantitative measure of the aerosol content in the entire atmospheric column."""]
                ),
            className="description-body"
        ),
        html.Div([
            html.Img(
                id='aod-image',
                src='./assets/metoffice/{date}/MSG_{date}{tstep:02}00_AOD_444x278.gif'.format(date=aod_end_date, tstep=0),
                alt='MetOffice AOD - NOT AVAILABLE',
                ),
            html.Div(
                obs_time_slider(div='obs-aod'),
                className="layout-dropdown",
            )],
            className='centered-image',
        ),
        html.Div(
            dcc.Interval(id='obs-aod-slider-interval',
                interval=1000,
                n_intervals=0,
                disabled=True
        )),
    ]

    visibility_children = [
        html.Span(
            html.P(
                "Visibility"
                ),
            className="description-title"
        ),
        html.Span(
            html.P([
                html.B("""You can explore key observations that can be used to track dust events. """),
                """All observations are kindly offered by Partners of the WMO Barcelona Dust Regional Center. The reduction of VISIBILITY is an indirect measure of the occurrence of sand and dust storms on the surface.""",
                ]),
            className="description-body"
        ),
        html.Div(
            id='obs-vis-graph',
            children=[],
            className='graph-with-slider'
        ),
#        dbc.Spinner(
#        ),
        html.Div([
            obs_time_slider(div='obs-vis',
                start=0,
                end=18,
                step=6,
                start_date=start_date,
                end_date=end_date
                ),
            #layout_view,
            html.Br(),
            html.Br(),
            html.Div(DISCLAIMER_NO_FORECAST,
                className='disclaimer'),
            ],
            className="layout-dropdown rgb-layout-dropdown",
        ),
    ]

    windows = {
        'rgb': rgb_children,
        # 'aod': aod_children,
        'visibility': visibility_children,
    }
    
    return dcc.Tab(label='Observations',
        id='observations-tab',
        value='observations-tab',
        className='horizontal-menu',
        children=windows[window],
    )

def sidebar_observations(option='rgb'):
    """ Build the observations sidebar"""

    #Highlight the selected section
    rgb_style = { 'fontWeight': 'bold' }
    visibility_style = { 'fontWeight': 'normal' }
    if option == 'visibility':
        rgb_style={ 'fontWeight': 'normal' }
        visibility_style= { 'fontWeight': 'bold' }

    return [html.Div([
        html.Label("Variable"),
        dcc.Dropdown(
            id='variable-dropdown-observation',
            options=[
                {'label': 'RGB', 'value': 'rgb'},
                # {'label': 'AOD', 'value': 'aod'},
                {'label': 'Visibility', 'value': 'visibility'}
            ],
            value=option,
            clearable=False,
            searchable=False,
            disabled=True
            # optionHeight=70,
        )],
        id='observations-variable',
        className="sidebar-first-item",
    ),
    html.Label("Column integrated"),
    html.Div([
        dbc.Button("EUMETSAT RGB",
            color="link",
            id='rgb', 
            style=rgb_style
        )],
        className="sidebar-item",
    ),
#     html.Div([
#         dbc.Button("MetOffice AOD",
#             color="link",
#             id='aod'
#         )],
#         className="sidebar-item",
#     ),
    html.Label("Surface"),
    html.Div([
        dbc.Button("Visibility",
            color="link",
            id='visibility',
            style=visibility_style
        )],
        className="sidebar-item",
    ),
]
