import cdstoolbox as ct
from datetime import datetime 
import calendar

"""
This toolbox application allows the user to retrieve all of the data for the whole of the month of January of the selected year.
It then creates a list of times for the day to extract, in this case between 00UTC and 08UTC of each day and selects an area.
The data is concatenated together and returned as a single NetCDF File.
"""

# Define Variables
VARIABLES = ['mean_radiant_temperature','universal_thermal_climate_index'] 
YEARS = {str(year):str(year) for year in range(1979,datetime.now().year + 1)} 
MONTHS = ['01']
DAYS = ['%02d'%(dy) for dy in range(1,32)]

# Page Layout 
layout = {
    'output_align': 'bottom',
    'input_ncols':3
    }

@ct.application(title='Universal Thermal Climate Index derived from reanalysis',layout=layout)
@ct.input.dropdown('variable', label='Variable', values=VARIABLES, default='universal_thermal_climate_index')
@ct.input.dropdown('year', label='Year', values=YEARS.keys(), default='2019') 
@ct.output.download()

def retrieve_data(variable,year) : 
    output = []

    # Set the product type based on the year
    # Consolidated data available 19790101 - 20200228 
    # Intermediate data available 20190930 - 20200517 
        # Version 1.0 covers the entire period of the dataset.
         # See https://confluence.ecmwf.int/display/CEMS/UTCI+Dataset+-+Known+Issues
         # Version 1.1 is a repair run that covers :         
         # Intermediate : 20210714 - 20220214
         # Consolidated : 20210429 - 20211231



    if int(year) < 2020:
        product_type='consolidated_dataset' 
    else:
	    product_type='intermediate_dataset'

    # Construct List Comprehension of the times we want 00UTC to 08UTC in this case
    times = [[f'{year}-{m}-{d:02d}T00', f'{year}-{m}-{d:02d}T08'] for m in MONTHS for d in range(1,calendar.mdays[int(m)]+1) ]
    # Retrieve the 1 year data for 
    data = ct.catalogue.retrieve( 
        'derived-utci-historical',
	    {
            'variable':variable,
            'year':year,
            'month':MONTHS,
            'day':DAYS,
            'product_type':product_type,
            'version':'1.0',
	    },
    )
	# Loop over the List of times we want to extract and append to output. 
    for t in times:
	    output.append(ct.cube.select(data, time=t, lat=[-45,-10], lon=[110,155] )) 
    return ct.cube.concat(output, dim='time')