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

import os
import json
import copy
from dash import html
import dash_leaflet as dl
import numpy as np
from dateutil.relativedelta import relativedelta

DIR_PATH = os.path.dirname(os.path.realpath(__file__))
COLORBARS = json.load(open(os.path.join(DIR_PATH, 'conf/colorbars.json')))
MODEBARS = json.load(open(os.path.join(DIR_PATH, 'conf/modebars.json')))

class MapHandler:

    def __init__(self):
        
        # TODO: Add common variables from all figure handlers here

        if self.name in COLORBARS:
            self.colorbar_info = COLORBARS[self.name]['colorbar']
        
        self.info_style = MODEBARS['info_style']

        return None

    def get_title(self, **kwargs):
        """ Return title from base title and elements """

        print('================= Retrieving figure title...')

        # Get selected and current datetime details
        rhour = self.rdatetime.strftime("%H")
        rday = self.rdatetime.strftime("%d")
        rmonth = self.rdatetime.strftime("%b")
        ryear = self.rdatetime.strftime("%Y")
        if hasattr(self, 'cdatetime'):
            shour = self.cdatetime.strftime("%H")
            sday = self.cdatetime.strftime("%d")
            smonth = self.cdatetime.strftime("%b")
            syear = self.cdatetime.strftime("%Y")

        # Get title elements that we want to show from base title
        # e.g. a dict with shour, sday, smonth, syear as keys
        title_elements = {}
        base_title_split = self.base_title.split("%(")
        for element in base_title_split[1:]:
            element_split = element.split(")")
            if len(element_split) > 1:
                title_element = element_split[0]
                if hasattr(self, title_element):
                    title_elements.update({title_element: getattr(self, title_element)})
                else:
                    title_elements.update({title_element: locals()[title_element]})

        # Create title from base and elements
        title = r'{}'.format(self.base_title % title_elements)

        return title
      
    def retrieve_cdatetime(self, tstep=0):
        """ Retrieve data from NetCDF file """

        tstep = int(tstep)
        time_attr = int(self.timesteps[tstep])

        # Calculate current datetime given the selected initial datetime and current timestep
        if self.what == 'days':
            cdatetime = self.rdatetime + relativedelta(days=time_attr)
        elif self.what == 'hours':
            cdatetime = self.rdatetime + relativedelta(hours=time_attr)
        elif self.what == 'minutes':
            cdatetime = self.rdatetime + relativedelta(minutes=time_attr)
        elif self.what == 'seconds':
            cdatetime = self.rdatetime + relativedelta(seconds=time_attr)

        return cdatetime

    def create_legend(self, colormap):
        
        print('================= Retrieving legend...')

        # Create categorical legend given the labels and its colors
        legend_items = []
        labels = colormap.keys()
        colors = colormap.values()

        for i, (label, color) in enumerate(zip(labels, colors)):
            legend_item = html.Div([html.Span(
                                        "",
                                        className="{}-legend-point".format(self.name),
                                        style={
                                            'backgroundColor': color,
                                            }
                                        ),
                                    html.Span(
                                        label,
                                        className="{}-legend-label".format(self.name),
                                        )
                                    ],
                                    style={ 'display': 'block' })
            legend_items.append(legend_item)

        legend = html.Div(legend_items, className="{}-legend".format(self.name))
        
        return legend

    def retrieve_info(self, name):
        
        print('================= Retrieving figure title box...')

        # Create figure title box
        info = html.Div(
            children=self.fig_title,
            id="{}-info".format(name),
            className="info",
            style=self.info_style
        )

        return info

    def retrieve_colorbar(self):
        
        print('================= Retrieving colorbar...')
        
        # Create colorbar
        colorbar = dl.Colorbar(**self.colorbar_info)

        return colorbar

class PointsFigureHandler(MapHandler):

    def __init__(self):

        super(PointsFigureHandler, self).__init__()

        # TODO: Add common variables from VisFigureHandler, Observations1dHandler and ScoresFigureHandler

        return None

    def retrieve_geojson(self, geojson_data, namespace):

        print('================= Retrieving geojson...')

        # Get points properties
        hideout = {"circleOptions": self.circle_options}
        if 'fillColor' not in hideout["circleOptions"].keys():
            hideout.update({'colorProp': "value",
                            'colorscale': self.colors})

        # Get geojson
        point_to_layer = namespace("pointToLayer")
        geojson = dl.GeoJSON(data=geojson_data,
                             options=dict(pointToLayer=point_to_layer,),
                             hideout=hideout)

        return geojson

class ContourFigureHandler(MapHandler):

    def __init__(self):

        super(ContourFigureHandler, self).__init__()

        # TODO: Add common variables from FigureHandler and ProbFigureHandler

        return None

