import pandas as pd
from glob import glob
import numpy as np
import os

ddir='/home/disk/rocinante/DATA/temp/chico/hyak/data_rbm/'
odir='/home/disk/rocinante/DATA/temp/chico/hyak/writeup/pub_temp/'
rdir='/home/disk/rocinante/DATA/temp/chico/hyak/data_ref/air_temp/'
pdir='/home/disk/rocinante/DATA/temp/chico/hyak/writeup/plots/'
tbl='/home/disk/rocinante/DATA/temp/chico/hyak/data_ref/tbl.csv'

gcms= [ 'access1.0_RCP45',
	'access1.0_RCP85',
	'access1.3_RCP85',
	'bcc-csm1.1_RCP85',
	'canesm2_RCP85',
	'ccsm4_RCP85',
	'csiro-mk3.6.0_RCP85',
	'fgoals-g2_RCP85',
	'gfdl-cm3_RCP85',
	'giss-e2-h_RCP85',
	'miroc5_RCP85',
	'mri-cgcm3_RCP85',
	'noresm1-m_RCP85',
	'pnnl']

#gcms = ['access1.0_RCP45','fgoals-g2_RCP85',	'gfdl-cm3_RCP85',	'pnnl']

pds=['1990s', '2050s', '2080s']
locs = [183, 196, 216, 266, 276, 277]

tdf = pd.read_csv(tbl)


arrWY = np.zeros((len(pds), len(gcms)))
arrA16 = np.zeros((len(pds), len(gcms)))


for iloc in range(len(locs)):
    loc = locs[iloc]
    lname = tdf[tdf.rbm_id == loc].name.values[0].strip()

    for igcm in range(len(gcms)):
        gcm = gcms[igcm]
        print(loc, lname, gcm)
        ldir = "{}/{}/".format(odir, lname)
        os.makedirs(ldir, exist_ok=True)
        
        ifile = "{}/{}/{}/output/seg/seg{}.temp".format(ddir, gcm, gcm, loc)
        cdf = pd.read_csv(ifile)
        cdf.index = pd.to_datetime(cdf.date, format='%Y-%m-%d %H:%M:%S')
        cdf.index.name = 'Date'
        cdf = cdf[['temp']]
        cdf.to_csv("{}/{}_{}_Hourly_Timeseries.csv".format(ldir, lname, gcm), header=['Temp'], float_format='%.2f')
        mdf = cdf.resample('1M').mean()
        mdf.to_csv("{}/{}_{}_Monthly_Timeseries.csv".format(ldir, lname, gcm), header=['Temp'], float_format='%.2f')
        dmax = cdf.resample('1D').max()
        da7d = dmax.rolling(7, center=True).mean()
    

        # Get Change in average max water year of 7DADMAX
        da7d['wyear'] = da7d.index.year + (da7d.index.month > 9)
        wyMAX = da7d.groupby('wyear').max()
        out = "{}/{}_{}_7DADMAX_AvgMaxWY_Timeseries.csv".format(ldir, lname, gcm)
        wyMAX.to_csv(out, float_format='%0.1f')
        
        wyMAX1990s = wyMAX[(wyMAX.index >= 1980) & (wyMAX.index <= 2009)].mean().temp
        wyMAX2050s = wyMAX[(wyMAX.index >= 2040) & (wyMAX.index <= 2069)].mean().temp
        wyMAX2080s = wyMAX[(wyMAX.index >= 2070) & (wyMAX.index <= 2099)].mean().temp
        #print(wyMAX1990s, wyMAX2050s, wyMAX2080s)
        arrWY[:, igcm] = [wyMAX1990s, wyMAX2050s, wyMAX2080s]
        
        
        # Get number of days with 7DADMAX above 16C for Jun15-Sep15
        da7d['abv16C'] = da7d.temp > 16
        js15 = da7d[((da7d.index.month == 6) & (da7d.index.day >= 15)) |
                    (da7d.index.month == 7) | (da7d.index.month == 8) |
                    ((da7d.index.month == 9) & (da7d.index.day <= 15))]
        js15_cnt = js15.groupby(js15.index.year).sum()[['abv16C']]
        js15_cnt_1990s = js15_cnt[(js15_cnt.index >= 1980) & (js15_cnt.index <= 2009)].abv16C.sum()
        js15_cnt_2050s = js15_cnt[(js15_cnt.index >= 2040) & (js15_cnt.index <= 2069)].abv16C.sum()
        js15_cnt_2080s = js15_cnt[(js15_cnt.index >= 2070) & (js15_cnt.index <= 2099)].abv16C.sum()
        js15_cnt.columns = ['Number of days above 16C']
        #print(js15_cnt_1990s, js15_cnt_2050s, js15_cnt_2080s)        
        out = "{}/{}_{}_7DADMAX_Jun15-Sep15_DaysAbv16C_Full.csv".format(ldir, lname, gcm)
        js15_cnt.to_csv(out)
        arrA16[:, igcm] = [js15_cnt_1990s, js15_cnt_2050s, js15_cnt_2080s]
        

    print(arrWY)
    #arrWY = arrWY - arrWY[0]
    dfWY = pd.DataFrame(arrWY, columns=gcms, index=pds)
    #dfWY = dfWY.iloc[1:].drop(['access1.0_RCP45', 'pnnl'], axis=1)
    #dfWY = dfWY.iloc[1:]    
    dfA16 = pd.DataFrame(arrA16, columns=gcms, index=pds)

    
    dfWY.to_csv("{}/{}_7DADMAX_AvgMaxWY_AllGCM.csv".format(ldir, lname), float_format='%.2f')
    dfA16.to_csv("{}/{}_7DADMAX_Jun15-Sep15_DaysAbv16C_AllGCM.csv".format(ldir, lname), float_format='%.0f')
    
