#!/usr/bin/python3

import otbApplication, argparse




def process_era5(erafile,ref,outfile):
    
#       otbcli_ManageNoData -in /data/BRETAGNE_T30UVU/CDS/ERA5-2m_T30UVU_20200121T175644.grib 
#        -out /data/BRETAGNE_T30UVU/CDS/ERA5-2m_T30UVU_20200121T175644_no.tif 
#        -mode changevalue -mode.changevalue.newv  283 
    manapp = otbApplication.Registry.CreateApplication("ManageNoData")
    manapp.SetParameterString("in",erafile)
    manapp.SetParameterString("out", str(2)+"temp.tif")
    manapp.SetParameterString("mode","changevalue")
    manapp.SetParameterFloat("mode.changevalue.newv",283)
    manapp.Execute()
    
#       otbcli_BandMathX -il /data/BRETAGNE_T30UVU/CDS/ERA5-2m_T30UVU_20200121T175644.grib 
#        -out /data/BRETAGNE_T30UVU/CDS/ERA5-2m_T30UVU_20200121T175644_bmx.tif 
#        -exp "(im1b1 == 283 ? im1b1 = mean(im1b1N5x5):im1b1)"
    bmxapp = otbApplication.Registry.CreateApplication("BandMathX")
    bmxapp.AddImageToParameterInputImageList("il",manapp.GetParameterOutputImage("out"))
    bmxapp.SetParameterString("out", str(3)+"temp.tif")
    bmxapp.SetParameterString("exp","(im1b1 == 283 ? im1b1 = mean(im1b1N5x5):im1b1)")
    bmxapp.Execute()
    
    eraapp = otbApplication.Registry.CreateApplication("Superimpose")
    eraapp.SetParameterInputImage("inm",bmxapp.GetParameterOutputImage("out"))
    eraapp.SetParameterString("out", outfile)
    eraapp.SetParameterString("interpolator","bco")
    eraapp.SetParameterString("inr",ref)
    eraapp.ExecuteAndWriteOutput()
    

if __name__ == "__main__":
    # Make parser object
    parser = argparse.ArgumentParser(description=
        """
        test
        """)
    
    parser.add_argument('-era', action='store', required=True, help='ERA5 grib file')
    parser.add_argument('-ref', action='store', required=True, help='reference img')
    parser.add_argument('-out', action='store', required=True, help='output')
#     parser.add_argument('-mask', action='store', required=True, help='Mask file to apply')
    
    args=parser.parse_args()
    
    process_era5(args.era,args.ref,args.out)