#!/usr/bin/python
# -*- coding: latin-1 -*-

import csv,glob,time,re
from stats import lpearsonr

def main():

    ini_fecha='2011/02/12'
    end_fecha='2011/03/24'
    estac='salvajina'
    Deltamax=24
    interv=3
    print estac

    tini=time.mktime(time.strptime(ini_fecha,"%Y/%m/%d"))
    tend=time.mktime(time.strptime(end_fecha,"%Y/%m/%d"))    

    epsafile=csv.reader(open('/home/arcesio/WRF/OPERA_E/ISAGEN/Caudales_Feb.csv','r'),delimiter=',')    

    ISA=[]
    dISA=[]
    A=[]
    Corr=[]
    acaudal=0.0
    while tini <= tend:
        fbreak=False
        hoy=time.strftime("%Y-%m-%d",time.localtime(tini-86400))
        ayer=time.strftime("%Y-%m-%d",time.localtime(tini-172800))

        if hoy=='2011-01-26' or hoy=='2011-01-27':
            tini=tini+86400
            continue

#        print '-----------'
#        print hoy
#        print '-----------'

        totaldia={}
        Delta=0
        while Delta <= Deltamax:
#            print 'Delta:',Delta
            totaldia[Delta]=0.0
            try:
                wrfhoy=csv.reader(open('/home/arcesio/WRF/OPERA_E/ISAGEN/'+estac+'_'+hoy+'escor.dat','r'),delimiter=',')
            except:
                Delta = Delta + interv
                fbreak=True
                break
            h1=24-interv-Delta+9
        #dia anterior:
            if Delta >= 9:
                try:
                    wrfayer=csv.reader(open('/home/arcesio/WRF/OPERA_E/ISAGEN/'+estac+'_'+ayer+'escor.dat','r'),delimiter=',')
                except:
                    Delta = Delta + interv
                    fbreak=True
                    break
                dia2=False
                for line in wrfayer:
                    hh=int(time.strftime("%H",time.strptime(line[0],"%Y-%m-%d_%H:00:00")))
                    if hh >= 24-interv and not dia2:
                        dia2=True
                        line=wrfayer.next()
                        hh=int(time.strftime("%H",time.strptime(line[0],"%Y-%m-%d_%H:00:00")))
                    if dia2 and hh >= h1:
                        totaldia[Delta]=totaldia[Delta]+float(line[1])+float(line[2])-float(line[3])
#                        print hh
        #dia actual
            dia2=False
            for line in wrfhoy:
                hh=int(time.strftime("%H",time.strptime(line[0],"%Y-%m-%d_%H:00:00")))
                if hh >= 24-interv and not dia2:
                    dia2=True
                    line=wrfhoy.next()
                    hh=int(time.strftime("%H",time.strptime(line[0],"%Y-%m-%d_%H:00:00")))
                if dia2 and hh >= 6-Delta and hh<=24-interv-Delta:
                    totaldia[Delta]=totaldia[Delta]+float(line[1])+float(line[2])-float(line[3])
#                    print hh
            Delta = Delta + interv

        if not fbreak :
    #Dato correspondiente EPSA
            tt=0
            while tt < tini:
                isaline=epsafile.next()
                tt=time.mktime(time.strptime(isaline[0],"%d/%m/%Y"))
            caudal=re.sub(',','.',str(isaline[3]))
            dcaudal=float(caudal)-acaudal
            acaudal=float(caudal)
            dia=time.strftime("%Y-%m-%d",time.localtime(tini))
            string=dia+', '
            for i in totaldia.values():
                string=string+str('%2.5f'%i)+', '

            print string+', '+caudal+', '+str(dcaudal)

            ISA.append(float(caudal))
            dISA.append(float(dcaudal))
            A.append(totaldia.values())

        tini=tini+86400

# Correlaciones (i=columnas,j=filas)
    for i in range(Deltamax/interv+1):
        B=[]
        for j in range(1,len(A)):
            B.append(A[j][i]-A[j-1][i])
        Corr.append(lpearsonr(B,dISA[1:]))
        
    string='           '
    for i in Corr:
        string=string+str('%2.5f'%i)+', '
    print string
    string='           '
    for i in totaldia.keys():
        string=string+'      '+str('%2s'%i)+','
    print string


            
if __name__ == "__main__":
  main()

