import pandas as pd
import sys
import os #llamadas al SO 
from datetime import date
from datetime import datetime

os.environ['TZ'] = 'UTC'
gdal_path = sys.argv[1]+'/' ## viene del config de la llamada '/cloudclusters/anaconda3/envs/gdal/bin/'
webpath   = sys.argv[2]+'/' ## viene del config de la llamada '/cloudclusters/default_site/data/goes/'
print('webpath',webpath)

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
print('Path: ',dname)

today = date.today()
print("-----------------------------")
print(datetime.now())


output = 'RR_'+datetime.now().strftime('%Y%m%d_%H')+'.tif'
print('new file - output : ',output)
cmd='cp '+webpath+'goes16_RR_1h.tif '+webpath+'RR/'+output
print(cmd)
os.system(cmd)

RR_files = os.listdir(webpath+'RR/')
RR_files.sort()
f_3h =RR_files[-3:]
f_6h =RR_files[-6:]
f_12h=RR_files[-12:]
f_24h=RR_files[-24:]
print('3h  ',f_3h)
print('6h  ',f_6h)
print('12h  ',f_12h)
print('24h ',f_24h)


bands='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print("---3H --------------")
comando=gdal_path+'gdal_calc.py '
suma='('
for i,f in enumerate(f_3h):
    suma=suma+bands[i]+'+'
    comando = comando + '-'+bands[i]+' '+webpath+'RR/'+f+' '
cmd=comando + '--calc=\''+suma[:-1]+')\' --outfile '+webpath+'goes16_RR_3h.tif --overwrite'
print(cmd)
os.system(cmd)
##gen_png('3h')

print("---6H --------------")
comando=gdal_path+'gdal_calc.py '
suma='('
for i,f in enumerate(f_6h):
    suma=suma+bands[i]+'+'
    comando = comando + '-'+bands[i]+' '+webpath+'RR/'+f+' '
cmd=comando + '--calc=\''+suma[:-1]+')\' --outfile '+webpath+'goes16_RR_6h.tif --overwrite'
print(cmd)
os.system(cmd)
##gen_png('6h')

print("---12H --------------")
comando=gdal_path+'gdal_calc.py '
suma='('
for i,f in enumerate(f_12h):
    suma=suma+bands[i]+'+'
    comando = comando + '-'+bands[i]+' '+webpath+'RR/'+f+' '
cmd=comando + '--calc=\''+suma[:-1]+')\' --outfile '+webpath+'goes16_RR_12h.tif --overwrite'
print(cmd)
os.system(cmd)
##gen_png('12h')

print("---24H --------------")
comando=gdal_path+'gdal_calc.py '
suma='('
for i,f in enumerate(f_24h):
    suma=suma+bands[i]+'+'
    comando = comando + '-'+bands[i]+' '+webpath+'RR/'+f+' '
cmd=comando + '--calc=\''+suma[:-1]+')\' --outfile '+webpath+'goes16_RR_24h.tif --overwrite'
print(cmd)
os.system(cmd)
##gen_png('24h')


##guardar total de 24h
if output[-6:-4]=='12':
    os.system('cp '+webpath+'goes16_RR_24h.tif '+webpath+'RR/RR_'+output[-15:-4]+'_24h.tif') #para guardar el diario
   ## os.system('cp '+webpath+'ghe_24h.png '+webpath+'ghe_'+date.today().strftime('%Y%m%d')+last_file[8:10]+'_24h.png') #para guardar el diario

