#!/usr/bin/env python
# -*- coding: UTF-8 -*-
outputDB = "dbname = GSM4-20130207 user = postgres"
testing = False
from WOSIS import *


def koeppenClimate():
    """"
    Script to generate names and descriptions for koeppen climate
    """
    # acronym list of koeppen climates in the WISE DB according to NB (07-02-2013), expanded by only base climates (HIR-07022013)
    Koeppenclimate=('Af','Am','Aw','As','BSh','BSk','BWh','BWk','BWn','Ca','Caf','Caw','Cb','Cbf','Cbw','Cc','Ccf','Ccw','Cs','Csa','Csb','Da','Daf','Das','Daw','Db','Dbf','Dbs','Dbw','Dc','Dcf','Dcs','Dcw','Dd','Ddf','Dds','Ddw','EF','ET','H','A','B','C','D','E')
    # Description Text for explanation of the first letter
    base = {'A':'Tropical (rainy) climates: Average temperature of every month is above 18 oC. These climates have no winter season. Annual rainfall is large and exceeds annual evaporation','B':'Dry: Potential evaporation exceeds precipitation on the average throughout the year. No water surplus; hence no permanent streams originate in B climate zones.','C':'Warm temperate mesothermal) climates: Coldest month has an average temperature under 18 oC, but above -3 oC. The C climates thus have both a summer and a winter season','D':'Snow (microthermal) climates: Coldest month average temperature under -3 oC. Average temperature of the warmest month above 10 oC, that isotherm corresponding approximately with pole-ward limit of forest growth','E':'Ice climates: A polar climate type with average temperature in no month averaging over 10 oC. These climates have no true summer','H':'Mountain/Highland climates'}
    # Description Text for explanation of the second letter
    subgroups={'S':'Steppe climate, a semiarid climate with about 380 to 760 mm of rainfall annually at low latitudes.','W':'Desert climate. Arid climate. Most regions included have less than 250 mm of rainfall annually.','f':'Moist. Adequate precipitation in all months. No dry season.','w':'Dry season in winter of the respective hemisphere (low-sun season)','s':'Dry season in summer of the respective hemisphere (high-sun season)','m':'Rainforest climate despite a short dry season in monsoon type of precipitation cycle.'}
    # Description Text for explanation of the third letter
    third={'a':'With hot summer; warmest month over 22 oC',' b':'With warm summer; warmest month below 22 oC','c':'With cool, short summer; fewer than four months over 10 oC','d':'With very cold winter; coldest months below - 38 oC','h':'Dry-hot; mean annual temperature over 18 oC','k':'Dry-cold; climates annual temperature under 18 oC'} 
    # Name Text for for the first two letter combinations
    names={'Af':'Tropical rainforest - moist','Am':'Tropical rainforest short dry season','As':'Tropical savanna','Aw':'Tropical savanna','BS':'Steppe climate','BW':'Desert climate','Cw':'Temperate rainy (humid mesothermal) climate with dry winter','Cf':'Temperate rainy humid mesothermal) climate moist all seasons','Cs':'Temperate rainy (humid mesothermal) climate with dry summer','Ca':'Temperate rainy (humid mesothermal) climate','Cb':'Warm temperate (mesothermal) climates','Cc':'Warm temperate (mesothermal) climates','Da':'Cool-humid continental climate with warm high-sun season','Db':'Cool-humid continental  with cool high-sun season','Dc':'Subarctic climate','Dd':'Subarctic with very cold low-sun season', 'Df':'Cold snowy forest (humid microthermal) climate moist in all seasons','Dw':'Cold snowy forest (humid microthermal) climate with dry winter','ET':'Tundra climate','EF':'Climates of perpetual frost (ice-caps)','H':'Mountain/Highland climates (undifferentiated)'}
    # Additional Name Text for for the third letter s
    namesadd={'a':' With hot summer','b':' With warm summer','c':' With cool, short summer','d':' With very cold winter','h':' Dry-hot','k':' Dry-cold','s':' - dry season in summer','m':' - short dry season','n':' -frequent fog',"f":' - moist','w':' - dry winter'} 
    # Name Text for for the single letter case
    singlename={'A':'Tropical (rainy) climates', 'B':'Dry', 'C':'Warm temperate (mesothermal) climates', 'D':'Snow (microthermal) climates', 'E':'Ice climates','H':'Mountain/Highland climates'}
    # process
    koeppenDict={}
    for code in Koeppenclimate:
            description =''; name = ''
            description = base[code[0]]
             
            if len(code)<=1:
                name = singlename[code[0]] 
            else:
                if code[1] in subgroups:
                    description += subgroups[code[1]]
                elif code[1] in third:  # letters sometimes exists in only on or the other dictionary, need to look it up in both 
                    description += third[code[1]]
                if code[:2] in names:
                    name = names[code[:2]]
                
            if len(code)>2:
                if code[2] in third: # letters sometimes exists in only on or the other dictionary, need to look it up in both 
                    description += third[code[2]]
                elif code[2] in subgroups:
                    description += subgroups[code[2]] 
                if code[2] in namesadd:
                    name+=namesadd[code[2]]
            koeppenDict[code]=(name,description)
    return koeppenDict



wosisDB = WOSIS(outputDB,testing=testing)

_,row=wosisDB.searchDomain('%climate%',nameAndDescriptionAndNotes=True,onlyId=True)
domainId=int(row[0][-1])
#domainId 138
#self,fkInt,fkCol,schemaName,tableName
rowHeader,rowsVD=wosisDB.getRecordFK(domainId,'DomainId','Attribute','DomainValue')
koeppenDic=koeppenClimate()

for acronym,value in koeppenDic.items():
 _,domainValueID=wosisDB.searchDomainValue(acronym,domainIdSearch=domainId)
 
 try:
    #if found do update 
    domainValueID=int(domainValueID[0][0])
    #print domainValueID
    #(self,schemaName,tableName,colName,recordPK,value):
    wosisDB.updateRecord("Attribute","DomainValue","Description",int(domainValueID),value[0])
   
    wosisDB.updateRecord("Attribute","DomainValue","Explanation",int(domainValueID),str(value[1]))
    
    #print wosisDB.searchDomainValue(acronym,domainValueID,onlyId=False)
 except Exception as e:
    #if not found we add it
    
     print wosisDB.insertRecord("Attribute","DomainValue",{'DomainId':int(domainId),
                                                                         'Value':acronym,
                                                                         'Description':value[0],
                                                                         'Explanation':value[1]})







print "done"