# Generate A counting of rainfall events
# Daryl Herzmann 16 Mar 2005

import constants
import mx.DateTime


# Data is generated by genMonthly.py

def write(mydb, out, station):
    out.write("""# NUMBER OF SNOWY DAYS PER MONTH PER YEAR
# Days with a trace of snowfall reported are not included
YEAR   JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC ANN   
""")

    rs = mydb.query("SELECT * from r_monthly WHERE station = '%s'" % (
                                    station,) ).dictresult()

    db = {}
    for i in range(len(rs)):
        ts = rs[i]["monthdate"]
        db[ts] = int(rs[i]["snow_days"])

    for yr in range(constants.startyear(station), constants._ENDYEAR):
        tot = 0
        out.write("%s   " % (yr,) )
        for mo in range(1, 13):
            cnt = db["%s-%02i-01" % (yr, mo)]
            ts = mx.DateTime.DateTime(yr,mo,1)
            if (ts >= constants._ARCHIVEENDTS):
                out.write("%3s " % ("M",) )
                continue
      
            out.write("%3i " % (cnt,))
            tot += cnt
        out.write("%3i\n" % (tot,))

    rs = mydb.query("""select extract(month from monthdate) as month, 
    stddev(snow_days), avg(snow_days) from r_monthly 
    WHERE station = '%s' GROUP by month ORDER by month ASC""" % (
                            station,) ).dictresult()

    db = {}
    for i in range(len(rs)):
        db[ int(rs[i]["month"]) ] = rs[i]
  
    rs = mydb.query("""SELECT avg(cnt), stddev(cnt) from ( 
       select extract(year from monthdate) as year, 
       sum(snow_days) as cnt from r_monthly 
       WHERE station = '%s' GROUP by year) as foo""" % (station,) ).dictresult()
    yrStd = rs[0]['stddev']
    yrAvg = rs[0]['avg']

    out.write("STDDEV ")
    for mo in range(1, 13):
        out.write("%3.0f " % (db[mo]['stddev'],))
    out.write("%3.0f\n" % (yrStd,) )
    out.write("AVG    ")
    for mo in range(1, 13):
        out.write("%3.0f " % (db[mo]['avg'],))
    out.write("%3.0f\n" % (yrAvg,))
