#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Tools module with functions related to plots """

from datetime import datetime as dt
from datetime import timedelta
import os
import logging

from data_handler import MapHandler
from data_handler import ForecastModelsFigureHandler
from data_handler import ForecastModelsTimeSeriesHandler
from data_handler import ForecastProbFigureHandler
from data_handler import ForecastWasFigureHandler
from data_handler import EvaluationGroundFigureHandler
from data_handler import EvaluationGroundTimeSeriesHandler
from data_handler import EvaluationSatelliteFigureHandler
from data_handler import EvaluationStatisticsFigureHandler
from data_handler import VisFigureHandler
from data_handler import DEBUG
from data_handler import MODELS
from data_handler import PATHS
from data_handler import END_DATE, DELAY, DELAY_DATE
from utils import get_currdate_tstep

def download_image_link(models, variable, curdate, tstep=0, anim=False):
    """ Generates links to animated gifs """
    logging.debug('CURRDIR %s', os.getcwd())
    filepath = "assets/comparison/{model}/{variable}/{year}/{month}/{curdate}_{model}_{tstep}.{ext}"

    if len(models) == 1:
        model = models[0]
        logging.debug('DOWNLOAD MODELS %s', model)
    else:
        logging.debug('DOWNLOAD ALL MODELS')
        model = "all"
    if anim:
        tstep = "loop"
        ext = "gif"
        logging.debug('DOWNLOAD LOOP')
    else:
        tstep = "%02d" % tstep
        ext = "png"
        logging.debug('DOWNLOAD PNG %s', tstep)

    filename = filepath.format(
                model=model,
                variable=variable.lower(),
                year=curdate[:4],
                month=curdate[4:6],
                curdate=curdate,
                tstep=tstep,
                ext=ext
            )
    logging.debug('DOWNLOAD FILENAME %s', filename)
    return filename 


def get_eval_timeseries(obs, start_date, end_date, var, idx, name, model):
    """ Retrieve timeseries """
    logging.debug('SERVER: OBS TS init for obs %s ... ', str(obs))
    th = EvaluationGroundTimeSeriesHandler(obs, start_date, end_date, var)
    logging.debug('SERVER: OBS TS generation ... ')
    return th.retrieve_timeseries(idx, name, model)


def get_timeseries(model, date, var, lat, lon, forecast=False):
    """ Retrieve timeseries """
    logging.debug('SERVER: TS init for models %s ... ', str(model))
    th = ForecastModelsTimeSeriesHandler(model, date, var)
    logging.debug('SERVER: TS generation ... ')
    return th.retrieve_timeseries(lat, lon, method='feather', forecast=forecast)


def get_single_point(model, date, tstep, var, lat, lon):
    """ Retrieve sigle point """
    logging.debug('SERVER: SINGLE POINT init for models %s ... ',str(model))
    th = ForecastModelsTimeSeriesHandler(model, date, var)
    logging.debug('SERVER: SINGLE POINT generation ... ')
    return th.retrieve_single_point(tstep, lat, lon)


def get_evaluation_comparison_aeronet_figure(sdate, edate, obs, var):
    """ Retrieve evaluation visual comparison figure """

    fh = EvaluationGroundFigureHandler(sdate, edate, obs, var)
    
    return fh.get_figure_layers()


def get_evaluation_comparison_modis_figure(var, obs, tstep=0, selected_date=END_DATE):
    """ Retrieve evaluation visual comparison figure """

    fh = EvaluationSatelliteFigureHandler(var, obs, tstep, selected_date)
    
    return fh.get_figure_layers()


def get_evaluation_statistics_figure(network=None, model=None, statistic=None, selection=None):
    """ Retrieve evaluation scores figure """
    
    logging.debug('SERVER: SCORES Figure init ... ')
    fh = EvaluationStatisticsFigureHandler(network, statistic, model, selection=selection)
    
    if network and model and statistic:
        logging.debug('SERVER: SCORES Figure generation ... ')
    else:
        logging.debug('SERVER: NO SCORES Figure')
    
    return fh.get_figure_layers()


def get_model_figure(var, model, tstep=0, hour=None, selected_date=END_DATE, aspect=(1, 1)):
    """ Retrieve figure """

    logging.debug("*** %s %s %s %s %s *****", model, var, selected_date, tstep, hour)

    try:
        selected_date = dt.strptime(
            selected_date, "%Y-%m-%d").strftime("%Y%m%d")
    except:
        pass

    if model in MODELS:
        model_start = MODELS[model]['start']
        model_start_before = ('start_before' in MODELS[model]) and MODELS[model]['start_before'] or False
        current_time_before = (DELAY_DATE and dt.strptime(selected_date, "%Y%m%d") < dt.strptime(DELAY_DATE, "%Y%m%d"))
        logging.debug(f"""
              ***************************** SERVER: Figure init *******************************
              * DELAY: {DELAY}, DELAY_DATE: {DELAY_DATE}, SELECTED DATE: {selected_date}, CURR_BEFORE: {current_time_before}    *
              * MODEL: {model}, MODEL_START: {model_start}, MODEL_START_DELAYED: {model_start_before} *
              *********************************************************************************
              """)
        # If current date is later than the delay date and the model_start is 12
        # or current date is before than the delay date and the model_start
        selected_date, tstep, _ = get_currdate_tstep(model_start, model_start_before, current_time_before, DELAY, selected_date, tstep)

    logging.debug(' %s %s %s %s %s', var, model, tstep, hour, selected_date)
    if var:
        logging.debug('SERVER: MODELS Figure init ... ')
        fh = ForecastModelsFigureHandler(var=var, model=model, tstep=tstep, hour=hour, selected_date=selected_date)
        logging.debug('SERVER: MODELS Figure generation ... ')
        return fh.get_figure_layers(tstep=tstep, hour=hour, aspect=aspect)

    logging.debug('SERVER: NO MODELS Figure')
    return ForecastModelsFigureHandler().get_figure_layers()


def get_prob_figure(var, prob=None, day=0, selected_date=END_DATE):
    """ Retrieve figure """
    logging.debug(' %s %s %s',prob, day, selected_date)
    try:
        selected_date = dt.strptime(
            selected_date, "%Y-%m-%d").strftime("%Y%m%d")
    except:
        pass
    logging.debug(' %s %s %s', prob, day, selected_date)
    if prob:
        logging.debug('SERVER: PROB Figure init ... ')
        fh = ForecastProbFigureHandler(var=var, prob=prob, selected_date=selected_date)
        logging.debug('SERVER: PROB Figure generation ... ')
        return fh.get_figure_layers(day=day)
    logging.debug('SERVER: NO PROB Figure')
    return ForecastProbFigureHandler().get_figure_layers()


def get_was_figure(was=None, day=0, selected_date=END_DATE):
    """ Retrieve figure """
    logging.debug(' %s %s %s', was, day, selected_date)
    try:
        selected_date = dt.strptime(
            selected_date, "%Y-%m-%d").strftime("%Y%m%d")
    except:
        pass
    logging.debug(' %s %s %s', was, day, selected_date)
    if was:
        logging.debug('SERVER: WAS Figure init ... ')
        fh = ForecastWasFigureHandler(was=was, selected_date=selected_date)
        logging.debug('SERVER: WAS Figure generation ... ')
        return fh.get_figure_layers(day=day)
    logging.debug('SERVER: NO WAS Figure')
    return ForecastWasFigureHandler().get_figure_layers()


def get_vis_figure(tstep=0, selected_date=END_DATE):
    """ Retrieve figure """
    logging.debug(' %s %s', tstep, selected_date)
    try:
        selected_date = dt.strptime(
            selected_date, "%Y-%m-%d").strftime("%Y%m%d")
    except:
        pass
    logging.debug(' %s %s', tstep, selected_date)
    if tstep is not None:
        logging.debug('SERVER: VIS Figure init ... ')
        fh = VisFigureHandler(selected_date=selected_date)
        logging.debug('SERVER: VIS Figure generation ... ')
        return fh.get_figure_layers(tstep=tstep)
    logging.debug('SERVER: NO VIS Figure')
    return VisFigureHandler().get_figure_layers()


def get_figure(selected_date=END_DATE, tstep=0, static=True, aspect=(1, 1), center=None,
               view='carto-positron', zoom=None, layers=None, index=None, tag='empty'):
    """ Retrieve figure """
    logging.debug('***** SERVER: Figure generation: CURR_DATE %s TSTEP %s *****', selected_date, tstep)
    
    fh = MapHandler()
    return fh.retrieve_fig(aspect=aspect, center=center, selected_tiles=view, 
                           zoom=zoom, tag=tag, index=index, layers=layers)
