#!/python24/python.exe

import os
import string
import cStringIO
import cgi
import sys
import urllib2
import urllib
import traceback

################# FUNZIONI ###############
def prova():

#  if azione == 'MI':

#     try:
        data1 = FormattaDataFile(day1,month1,year1)
        data2 = FormattaDataFile(day2,month2,year2)
#        dataFile=(data1+'_to_'+data2)
#        path=('C:\PythonWeb\scripts\\'+dataFile+'\pio.dat')

#        fsock = open(path, "rb", 0)
#        os.system( 'C:\PythonWeb\scripts\Batch.exe' )

### CHIAMATA alla funzione crea grafici ###
#        crea_grafici()

        if bacino == 'DeseZero':
           flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_dese_zero.html')
           for line in flob.readlines(): print line,
        elif bacino == 'VallMeol':
           flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_vallio_meolo.html')
           for line in flob.readlines(): print line,
        elif bacino == 'Marzenego':
           flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_marzenego.html')
           for line in flob.readlines(): print line,           
        elif bacino == 'Lus-Mene':
           flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_lusore_menegon.html')
           for line in flob.readlines(): print line,      
        elif bacino == 'CanaLova':
           flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_canale_di_lova.html')
           for line in flob.readlines(): print line,                                       
        elif bacino == 'Mntlbano':
           flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_canale_montalbano.html')
           for line in flob.readlines(): print line,                            
        elif bacino == 'BacnoSud':
           flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_bacino_scolante_sud.html')
           for line in flob.readlines(): print line,                 
        elif bacino == 'BrntaNov':
           flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_naviglio_brenta.html')
           for line in flob.readlines(): print line,                 
        elif bacino == 'Fme-Sile':
           flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_fiume_sile.html')
           for line in flob.readlines(): print line,                    
#     except IOError:
#        os.system( 'C:\PythonWeb\scripts\Batch_Kriging.exe' )
#        os.system( 'C:\PythonWeb\scripts\Batch.exe' )
#        if bacino == 'DeseZero':
#           flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_dese_zero.html')
#           for line in flob.readlines(): print line,
#        else:
#           flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_vallio_meolo.html')
#           for line in flob.readlines(): print line,

#  if azione == 'KR':

#     os.system( 'C:\PythonWeb\scripts\Batch_Kriging.exe' )
#     flob = urllib2.urlopen('http://localhost:8080/index.html')
#     for line in flob.readlines(): print line,

#     try:
#        dataFile=(data1+'_to_'+data2)
#        path=('C:\PythonWeb\scripts\\'+dataFile)
#        lista=os.listdir(path)
#        flob = urllib2.urlopen('http://localhost:8080/doc/html/bacino.html')
#        for line in flob.readlines(): print line,
#     except IOError:
#        flob = urllib2.urlopen('http://localhost:8080/doc/html/menu_dese_zero.html')
#        for line in flob.readlines(): print line,

#     os.system( 'C:\PythonWeb\scripts\Batch.exe' )
#  else:
#     os.system( 'C:\PythonWeb\scripts\Batch_Kriging.exe' )


def FormattaDataFile(day,month,year):
    mesechar = {1: 'gen', 2: 'feb', 3:'mar', 4:'apr', 5:'mag', 6:'giu', 7:'lug', 8:'ago', 9:'set', 10:'ott', 11:'nov', 12:'dic'}
    for k, v in mesechar.iteritems():
        if k == month:
            monthformat = mesechar[k]
    datina = str(year)
    na = datina[2:]
    if len(str(day)) == 1:
       daynew = ('0'+str(day))
    else:
       daynew=day

    data = (str(daynew)+'-'+str(monthformat)+'-'+na)
    return data

#def copyfile(src,src1,dst1,dst):
#    names = os.listdir(dst1)
#    for name in names:
#        print name
#        names1 = os.listdir(src)
#        for name1 in names1:
#            print name1
#            if name == name1:
 #              shutil.rmtree(dst)

#    shutil.copytree(src1, dst)

#    pathrmdirs=src1
 #   removedirs(pathrmdirs)

#def removedirs(pathrmdirs):
#    shutil.rmtree(pathrmdirs)

#def removefile(day1,month1,year1,day2,month2,year2,):
#    data1 = FormattaDataFile(day1,month1,year1)
#    data2 = FormattaDataFile(day2,month2,year2)
#    dataFile=(data1+'_to_'+data2)

#    pathrmdirs=('C:\PythonWeb\scripts\\'+dataFile)
#    removedirs(pathrmdirs)

#    pathrmdirs=('C:\PythonWeb\scripts\contorno')
#    removedirs(pathrmdirs)

#    pathrmdirs=('C:\PythonWeb\scripts\temp')
#    removedirs(pathrmdirs)

#    pathrmdirs=('C:\PythonWeb\scripts\RIS')
#    removedirs(pathrmdirs)

#    lista=os.listdir(path)
#    print lista
#    for File in os.listdir(path):
#       print File
#        os.remove(File)

#    files=os.listdir(path)

#    for x in files:
#        fullpath=os.path.join(path, x)
#        print fullpath
#        if os.path.isfile(fullpath):
#            f=os.remove
#            rmgeneric(fullpath, f)
#        elif os.path.isdir(fullpath):
#            removeall(fullpath)
#            f=os.rmdir
#            rmgeneric(fullpath, f)

#def crea_grafici():
#   os.system( 'C:\PythonWeb\scripts\CallGraphic.exe' )

def write_input_info(bacino,day1,month1,year1,day2,month2,year2,datalast,giorniinizio):
    data1 = FormattaDataFile(day1,month1,year1)
    data2 = FormattaDataFile(day2,month2,year2)
# data3
    if day1 > 1:
        data3 = FormattaDataFile(day1-1,month1,year1)
    elif month1 == 1:
        data3 = FormattaDataFile(31,12,year1-1)
    elif month1 == 2:
        data3 = FormattaDataFile(31,1,year1)
    elif month1 == 3:
        data3 = FormattaDataFile(28,2,year1)
    elif month1 == 4:
        data3 = FormattaDataFile(31,3,year1)
    elif month1 == 5:
        data3 = FormattaDataFile(30,4,year1)
    elif month1 == 6:
        data3 = FormattaDataFile(31,5,year1)
    elif month1 == 7:
        data3 = FormattaDataFile(30,6,year1)
    elif month1 == 8:
        data3 = FormattaDataFile(31,7,year1)
    elif month1 == 9:
        data3 = FormattaDataFile(31,8,year1)
    elif month1 == 10:
        data3 = FormattaDataFile(30,9,year1)
    elif month1 == 11:
        data3 = FormattaDataFile(31,10,year1)
    elif month1 == 12:
        data3 = FormattaDataFile(30,11,year1)

    info_out = open("C:\PythonWeb\scripts\info.txt","w")
    info_out.write(bacino+'\n'+data1+' '+data2+' '+str(datalast+1)+'\n'+str(giorniinizio)+'\n'+data3+' '+azione)
    info_out.close()

def daycount(year, month, day):
    """"This is an implementation of the Julian Day system. This
    is a continuous count of days from January 1, 4713 B.C.
    Given a date in integers it returns an integer value for the date
    This represents it's Julian Day number as above.
    This only works for dates represented using the the Gregorian
    calendar which was adopted in the US/UK on Oct. 15, 1582 - but
    at different times elsewhere (so historical dates may not be in this system....)."""
    if month < 3:
        year = year - 1
        month = month + 13
    else:
        month = month + 1
    A = int(year/100)
    B = 2 - A + int(A/4)
    return int(365.25*year) + int(30.6001*month) + B + day + 1720995

def daysbetween(day1, month1, year1, day2, month2, year2):
    """Given two dates it returns the number of days between them.
    If date1 is earlier than date2 then the result will be positive."""
    count = daycount(year2, month2, day2) - daycount(year1, month1, day1)
    return count
################# DATA1 ##################
def formattaData(data1, data2):
   PosDay1 = string.find(data1, "-")
   day1 = data1[0:PosDay1]
   NewPosDay=data1[PosDay1+1:10]

   PosMonth1 = string.find(NewPosDay, "-")
   month1 = NewPosDay[0:PosMonth1]

   PosYear1 = len(data1)-4
   year1 = data1[PosYear1:len(data1)]

################# DATA2 ##################
   PosDay2 = string.find(data2, "-")

   day2 = data2[0:PosDay2]
   NewPosDay=data2[PosDay2+1:10]

   PosMonth2 = string.find(NewPosDay, "-")
   month2 = NewPosDay[0:PosMonth2]

   PosYear2 = len(data2)-4
   year2 = data2[PosYear2:len(data2)]

################# DATA2 ##################
   PosDay3 = string.find(data1, "-")

   day3 = data1[0:PosDay3]
   NewPosDay=data1[PosDay3+1:10]

   PosMonth3 = string.find(NewPosDay, "-")
   month3 = NewPosDay[0:PosMonth3]

   PosYear3 = len(data1)-4
   year3 = data1[PosYear3:len(data1)]

   return int(day1), int(month1), int(year1), int(day2), int(month2), int(year2), int(day3), int(month3), int(year3)

############# FINE FUNZIONI ##############

######### SCRITTURA PAGINA #########

print "Content-Type: text/html"     # HTML is following
print                               # blank line, end of headers

form = cgi.FieldStorage()

if form.has_key("data1"):
   data1 = form["data1"].value

if form.has_key("bacino"):
   bacino = form["bacino"].value

if form.has_key("data2"):
   data2 = form["data2"].value

if form.has_key("azione"):
   azione = form["azione"].value

datanum = formattaData(data1,data2)
day1 = datanum[0]
month1 = datanum[1]
year1 = datanum[2]
day2 = datanum[3]
month2 = datanum[4]
year2 = datanum[5]

day3 = 31
month3 = 12
year3 = int(year1) - 1
giorniinizio = daysbetween(day3, month3, year3, day1, month1, year1)

datalast =  daysbetween(day1, month1, year1, day2, month2, year2)

#if azione == 'KR':
#   bacino = 'DeseZero'

### CHIAMATA FUNZIONE SCRITTURA FILE INFO.TXT ###
write_input_info(bacino,day1,month1,year1,day2,month2,year2,datalast,giorniinizio)

### CHIAMATA FUNZIONE CALL MODULO .EXE ###
prova()

### CHIAMATA FUNZIONE RIMOZIONE FILES TEMPORANEI ###
#removefile(day1,month1,year1,day2,month2,year2)

### CHIAMATA FUNZIONE per copiare e poi cancellare la directory Risultati ###
#src=('C:\PythonWeb\scripts\Risultati')
#src1=('C:\PythonWeb\scripts\Risultati\\'+dataFile)
#dst1=('C:\PythonWeb\scripts\Risultati modello')
#dst=('C:\PythonWeb\scripts\Risultati modello\\'+dataFile)

#copyfile(src,src1,dst1,dst)

### SCRITTURA PAGINA BACINO ###
#flob = urllib2.urlopen('http://localhost:8080/doc/html/bacino.html')
#for line in flob.readlines(): print line,

