#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Interpolate NetCDF module
"""

import os
import subprocess
from glob import glob

def interpolate_netcdf(dates):
    """ Interpolates all netCDFs to the same 0.5 grid """

    models_path = "/data/thredds/models-repos/"
    output_path = '/data/daily_dashboard/prob/tmp/'
    lonlat = "-25,60,5,65"
    input_filedir = os.listdir(models_path)
    script_clean =   "rm -rvf "+output_path+"/*.nc"
    subprocess.call(script_clean, shell=True)
    for ifile_dir in input_filedir:
        if ifile_dir == 'NMMB-BSC':
            tpl = '*OPER.nc'
        elif ifile_dir == 'median':
            tpl = '*MEDIAN.nc'
        else:
            tpl = '*.nc'
        print (ifile_dir)
        for ifile in glob(f'/data/products/{ifile_dir}/archive/{dates}{tpl}'):
            if os.path.exists(output_path+"interpolated/"+os.path.basename(ifile)):
                print(output_path+"interpolated/"+os.path.basename(ifile), 'exists. Exit.')
                continue
            script =  "cdo -L -s -sellonlatbox,"+lonlat+" -remapbil,global_0.5  "+ifile+" "+\
                output_path+"interpolated/"+os.path.basename(ifile)
            print (script)
            subprocess.call(script, shell=True)

if __name__=="__main__":
    import sys
    #LonW, LonE, LatN, LatS
    curdate = sys.argv[1]
    interpolate_netcdf(curdate)
