import pytest
from datetime import datetime
from datetime import timedelta
import importlib
code = importlib.import_module('ines_core_map_handler')
from map_handler import END_DATE
from map_handler import FREQ

FMT_ISO = "%Y%m%d"
FMT_DASH = "%Y-%m-%d"
FMT_MON = "%d %b %Y"
FMT_MON_HR = f"%Hh {FMT_MON}"
FMT_HR = "%H:%M:%S"
FMT_DASH_HR = f"{FMT_DASH} {FMT_HR}"
EDATE_OBJ = datetime.strptime(END_DATE, FMT_ISO)

# =================== FIGURE HANDLER ============================
@pytest.fixture
def MapHandler():
    MapHandler = code.MapHandler()
    MapHandler.rdatetime = datetime.strptime("2023-04-30 00:00:00", "%Y-%m-%d %H:%M:%S")
    MapHandler.what = 'hours'
    MapHandler.timesteps = [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 
                            57, 60, 63, 66, 69, 72]
    return MapHandler

def test_get_center(MapHandler):
    assert MapHandler.get_center([35,45]) == [35, 45]
    assert MapHandler.get_center([-35,-45]) == [-35, -45]

def test_retrieve_cdatetime(MapHandler):
    assert str(MapHandler.retrieve_cdatetime(tstep=0)) == EDATE_OBJ.strftime(FMT_DASH_HR)  # '2023-04-30 12:00:00'
    assert str(MapHandler.retrieve_cdatetime(tstep=6)) == (EDATE_OBJ + timedelta(hours=6*FREQ)).strftime(FMT_DASH_HR)  # '2023-05-01 06:00:00'
    assert str(MapHandler.retrieve_cdatetime(tstep=12)) == (EDATE_OBJ + timedelta(hours=12*FREQ)).strftime(FMT_DASH_HR)  # '2022-05-02 00:00:00'

def test_get_title(MapHandler):

    model_name = "MULTI-MODEL"

    MapHandler.step = "{:02d}".format(0)
    MapHandler.cdatetime = MapHandler.retrieve_cdatetime(tstep=0)
    var_title = "Dust Optical Depth (550nm)<br>Valid: %(shour)sh %(sday)s %(smonth)s %(syear)s (H+%(step)s)"
    MapHandler.base_title = " ".join([model_name, var_title])
    assert MapHandler.get_title(varname='OD550_DUST', tstep=0) == 'MULTI-MODEL Dust Optical Depth (550nm)<br>Valid: {edate} (H+00)'.format(edate=EDATE_OBJ.strftime(FMT_MON_HR))
    
    MapHandler.step = "{:02d}".format(9*FREQ)
    MapHandler.cdatetime = MapHandler.retrieve_cdatetime(tstep=9)
    var_title = "Dust Surface Conc. (µg/m³)<br>Valid: %(shour)sh %(sday)s %(smonth)s %(syear)s (H+%(step)s)"
    MapHandler.base_title = " ".join([model_name, var_title])
    assert MapHandler.get_title(varname='SCONC_DUST', tstep=9) == 'MULTI-MODEL Dust Surface Conc. (µg/m³)<br>Valid: {edate} (H+27)'.format(edate=(EDATE_OBJ + timedelta(hours=9*FREQ)).strftime(FMT_MON_HR))

def test_hour_to_tstep(MapHandler):
    assert MapHandler.hour_to_tstep(0) == 0
    assert MapHandler.hour_to_tstep(3) == int(3/FREQ)
    assert MapHandler.hour_to_tstep(6) == int(6/FREQ)
    assert MapHandler.hour_to_tstep(36) == int(36/FREQ)
