import os, subprocess
from datetime import datetime
from dateutil.relativedelta import relativedelta
from utils import lm_ID, wrk_dir, out_dir

#===============================================================================
# Init
#
print('\n\n================================================================================')
#print('Running {0:s}...'.format(__file__))

ini_date = datetime(2017, 1, 1)
end_date = datetime(2023, 1, 1)

vname = 'T_2M'

#-------------------------------------------------------------------------------
# Compute montly averaged quantities
#
def monthlyAverages():
    cur_yearMonth = ini_date
    while cur_yearMonth < end_date:
        # outer loop on months

        # assemble run dir and path
        run_dir = cur_yearMonth.strftime('%y%m0100') + lm_ID
        run_path = os.path.join(wrk_dir, run_dir)
        fname = cur_yearMonth.strftime('lffd%Y%m????0000.nc')
        out_fname = 'avg_{0:s}.nc'.format(vname)
        fpath_glob = os.path.join(run_path, out_dir, fname)
        out_fpath  = os.path.join(run_path, out_dir, out_fname)

        if not os.path.isfile(out_fpath):
            # print info
            print('\tComputing average: ' + fpath_glob)
            # command
            command = 'cdo timmean -select,name={0:s} {1:s} {2:s}'.format(vname, fpath_glob, out_fpath)
            #print(command)
            job = subprocess.run(command, shell=True, stdout=subprocess.PIPE)
        else:
            # print info
            print('\tAlready computed average: ' + out_fpath)

        cur_yearMonth += relativedelta(months=1)

#-------------------------------------------------------------------------------
# Combine into yearly averaged quantities
#
def yearlyAverages():
    cur_year = ini_date
    while cur_year.year <= end_date.year:
        # outer loop on years

        # assemble run dir and path
        run_glob = cur_year.strftime('%y??0100') + lm_ID
        run_path = os.path.join(wrk_dir, run_glob)
        fname = 'avg_{0:s}.nc'.format(vname)
        out_fname = 'avg_{0:d}_{1:s}.nc'.format(cur_year.year, vname)
        fpath = os.path.join(run_path, out_dir, fname)
        out_fpath  = os.path.join(wrk_dir, out_fname)

        if not os.path.isfile(out_fpath):
            # print info
            print('\tComputing average: ' + fpath)
            # command
            command = 'cdo timmean -select,name={0:s} {1:s} {2:s}'.format(vname, fpath, out_fpath)
            #print(command)
            job = subprocess.run(command, shell=True, stdout=subprocess.PIPE)
        else:
            # print info
            print('\tAlready computed average: ' + out_fpath)
        cur_year += relativedelta(years=1)
