# coding: utf-8
import pandas as pd
tdata = pd.read_csv(
    '/work/EMIS/users/ktalgo/WO-144.3_hemi/Task06/2016v1_domain_total_emissions_CAPs.csv',
    index_col=['sector', 'poll']
)
elog = pd.read_csv('emis.csv', skipinitialspace=True)
# .query('SECTOR != "othar" and SECTOR != "othpt" and SECTOR != "othafdust_adj" and SECTOR != "othptdust_adj" and SECTOR != "ptfire_othna" and SECTOR != "onroad_mex" and SECTOR != "onroad_can"')

sectors = elog.SECTOR.unique()
elog.set_index(['MONTH', 'SOURC', 'SECTOR', 'DAYTYPE', 'UNIT01'], inplace=True)
pollutants = ['NOX', 'CO', 'SO2', 'NO', 'NO2']
#          J,  F,  M,  A,  M,  J,  J,  A,  S,  O,  N,  D
dayspm = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
months = [201601]
tonsvals = {}
refvals = {}
newvals = {}
Ggvals = {}
count = {}
skip = {}
for month in months:
  if month == 201601:
    vkey = 'jan_value'
  for sector in sectors:
    if sector.startswith('cmv'):
        sumsector = sector + '_12'
    else:
        sumsector = sector

    for poll in pollutants:
        wekey = month, 'HEMCO', sector, 'weekend', 'ton' + poll
        wdkey = month, 'HEMCO', sector, 'weekday', 'ton' + poll
        if wekey not in elog.index:
            print('Skipping', month, sector, poll)
            skip.setdefault(poll, 0)
            skip[poll] += 1
            continue
        else:
            we = elog.loc[wekey]
            wd = elog.loc[wdkey]
            if poll not in tonsvals: 
                tonsvals[poll] = 0
                newvals[poll] = 0
                refvals[poll] = 0
                Ggvals[poll, wd.UNIT02] = 0
                count[poll] = 0
            ton = (we.VALUE01 * 2/7. + wd.VALUE01 * 5/7.) * dayspm[month - 201601]
            Gg = (we.VALUE02 * 2/7. + wd.VALUE02 * 5/7.) * dayspm[month - 201601]
            count[poll] += 1
            tonsvals[poll] += ton
            Ggvals[poll, wd.UNIT02] += Gg
            try:
              ref = tdata.loc[sumsector, poll][vkey]
              print('{},{},{},{:.2g},{:.2g},{:.2f}'.format(month, sector, poll, ref, ton, ton/ref))
              refvals[poll] += ref
              newvals[poll] += ton
            except Exception as e:
              print('No ref', month, sector, poll, e, ton)
        
