# AUTOGENERATED! DO NOT EDIT! File to edit: 00_data.ipynb (unless otherwise specified).

__all__ = ['download_era5_land']

# Cell
import cdsapi
import os

# Cell
def download_era5_land(variable, area, year, month, data_dir, ext='grib'):
    """
    Download ERA5 Land data from Copernicus using the cdsapi. If
    the file already exists in data_dir it won't be downloaded. Data is downloaded
    in grib format.

    https://cds.climate.copernicus.eu/cdsapp#!/dataset/reanalysis-era5-land?tab=overview

    variable: str, see ERA5-Land documentation for available variables
    area: list, bounding box of latitude/longitude coordinates in the following form: \[North, West, South, East]
    year: int, year to retrieve data for
    month: int, month to retrieve data for
    data_dir: str, local path to save downloaded data to
    """

    m_str = f'{month}'.zfill(2)
    filename = f'{data_dir}/{year}{m_str}_{variable}.{ext}'

    # if the file has already been downloaded return early
    if os.path.isfile(filename):
        print(f'{filename} already exists..skipping.')
        return

    days = [str(i+1) for i in range(calendar.monthrange(year, month)[1])]
    times = [f'{str(i).zfill(2)}:00' for i in range(24)]

    api_options = {
        'variable': variable,
        'area': area,
        'year': f'{year}',
        'month': m_str,
        'day': days,
        'time': times,
        'format': ext,
    }

    client = cdsapi.Client()
    try:
        print(f'Retrieving with the following options and filename: {api_options}, {filename}')
        client.retrieve('reanalysis-era5-land', api_options, filename)
    except Exception as e:
        print(f'{e}')

    return