#!/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

from data_handler import FigureHandler
from data_handler import WasFigureHandler
from data_handler import ProbFigureHandler
from data_handler import VisFigureHandler
from data_handler import ScoresFigureHandler
from data_handler import TimeSeriesHandler
from data_handler import ObsTimeSeriesHandler
from data_handler import Observations1dHandler
from data_handler import DEBUG
from data_handler import MODELS
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 """
    if DEBUG:
        print('CURRDIR', os.getcwd())
    filepath = "assets/comparison/{model}/{variable}/{year}/{month}/{curdate}_{model}_{tstep}.{ext}"

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

    filename = filepath.format(
                model=model,
                variable=variable.lower(),
                year=curdate[:4],
                month=curdate[4:6],
                curdate=curdate,
                tstep=tstep,
                ext=ext
            )
    if DEBUG:
        print('DOWNLOAD FILENAME', filename)
    return filename 


def get_eval_timeseries(obs, start_date, end_date, var, idx, name, model):
    """ Retrieve timeseries """
    if DEBUG:
        print('SERVER: OBS TS init for obs {} ... '.format(str(obs)))
    th = ObsTimeSeriesHandler(obs, start_date, end_date, var)
    if DEBUG:
        print('SERVER: OBS TS generation ... ')
    return th.retrieve_timeseries(idx, name, model)


def get_timeseries(model, date, var, lat, lon, forecast=False):
    """ Retrieve timeseries """
    if DEBUG:
        print('SERVER: TS init for models {} ... '.format(str(model)))
    th = TimeSeriesHandler(model, date, var)
    if DEBUG:
        print('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 """
    if DEBUG:
        print('SERVER: SINGLE POINT init for models {} ... '.format(str(model)))
    th = TimeSeriesHandler(model, date, var)
    if DEBUG:
        print('SERVER: SINGLE POINT generation ... ')
    return th.retrieve_single_point(tstep, lat, lon)


def get_obs1d(sdate, edate, obs, var):
    """ Retrieve 1D observation """
    obs_handler = Observations1dHandler(sdate, edate, obs)
    return obs_handler.generate_obs1d_tstep_trace(var)


def get_scores_figure(network, model, statistic, selection=END_DATE):
    """ Retrieve 1D observation """
    fh = ScoresFigureHandler(network, statistic, selection)
    return fh.retrieve_scores(model) 


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


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


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


def get_models_figure(model=None, var=None, selected_date=END_DATE, tstep=0,
        hour=None, static=True, aspect=(1, 1), center=None,
        view='carto-positron', zoom=None, layer=None, tag='empty'):
    """ Retrieve figure """
    if DEBUG:
        print("***", model, var, selected_date, tstep, hour, "***")
    try:
        selected_date = dt.strptime(
            selected_date, "%Y-%m-%d %H:%M:%S").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"))
        if DEBUG:
            print(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)

        if DEBUG:
            print('***** SERVER: Figure generation: CURR_DATE', selected_date, 'TSTEP', tstep, '*****')
        #  return True
        fh = FigureHandler(model, selected_date)
        return fh.retrieve_var_tstep(var, tstep, hour, static, aspect, center,
                                     view, zoom, layer, tag)

    if DEBUG:
        print('SERVER: No Figure')
    return FigureHandler().retrieve_var_tstep(layer=layer, center=center, selected_tiles=view, zoom=zoom, tag=tag)
