import tempfile, shutil, os, sys, json, traceback, re

from decimal import *

from mmap import mmap, ACCESS_READ
from xlrd import open_workbook
from xlutils.copy import copy
from pprint import pprint
import pdb
workbook = None
# keep track of row indexes for each sheet. This value will be the 0-based
# index of the row where to write the next line of data in the given sheet
electricitySupplyRow = 1
electricityUtilityRow = 1
naturalGasSupplyRow = 1
naturalGasUtilityRow = 1

STD_OFFER_ELECTRIC_SHEET_INDEX = 0
COMP_SUPPLY_ELECTRIC_SHEET_INDEX = 1
STD_OFFER_NATURAL_GAS_SHEET_INDEX = 2
COMP_SUPPLY_NATURAL_GAS_SHEET_INDEX = 3

def main():
    global workbook
    args = sys.argv[1:]
    if not args:
        raise Exception('template excel workbook missing')
    templateWorkbookPath = args[0]
    readOnlyWorkbook = open_workbook(templateWorkbookPath)
    workbook = copy(readOnlyWorkbook)
    # var items = ijson.items(sys.stdin, '')
    while 1:
        line = sys.stdin.readline()
        if not line:
            break
        try:
            data = json.loads(line)
            processInvoice(data)
        except Exception, err:
            raise err
    workbook.save(sys.stdout)


def processInvoice(invoice):
    # write to the appropriate spreadsheet based on the type of invoice.
    # The invoice could be natural gas or electricty & supply or utility T&D
    invoiceType = invoice['invoiceType']
    commodity = invoiceType['commodity']
    typeOfSupply = invoiceType['type']
    # Natural Gas
    if (commodity == 'natural gas'):
        if (typeOfSupply == 'supplier'):
            outputToNaturalGasSupplySheet(invoice)
            return
        if (typeOfSupply == 'utility'):
            outputToNaturalGasUtilitySheet(invoice)
            return
        return

    # Electricity
    elif (commodity == 'electricity'):
        if (typeOfSupply == 'supplier'):
            outputToElectricitySupplySheet(invoice)
            return
        if (typeOfSupply == 'utility'):
            outputToElectricityUtilitySheet(invoice)
            return
    else:
        sys.stderr.write('unknown commodity type: ' + commodity)


# dates are stored as moment strings and look like
# "2011-07-25T04:00:00.000Z"
# We want to strip of the entire time piece and just get the date
#
# @input "2011-07-25T04:00:00.000Z"
# @output "2011-07-25"
def dateStringFromMoment(input):
    input = re.sub("T.*$", "", input)
    return input

def isDict(input):
    return isinstance(input, dict)

def isSet(key, data):
    if not isDict(data):
        return False
    if (data.get(key) and data[key] != 'null'):
        return True
    return False


def outputToElectricityUtilitySheet(data):
    global workbook, electricityUtilityRow
    try:
        sheet = workbook.get_sheet(STD_OFFER_ELECTRIC_SHEET_INDEX)
        if (isSet('accountNumber', data)):
            sheet.write(electricityUtilityRow, 0, data['accountNumber'])

        if (isSet('meterNumber', data)):
            sheet.write(electricityUtilityRow, 1, data['meterNumber'])
        if (isSet('fromDate', data)):
            sheet.write(electricityUtilityRow, 2, data['fromDate'])

        if (isSet('toDate', data)):
            sheet.write(electricityUtilityRow, 3, data['toDate'])


        if (isSet('days', data)):
            sheet.write(electricityUtilityRow, 4, Decimal(data['days']))

        if (isSet('readType', data)):
            sheet.write(electricityUtilityRow, 5, data['readType'])

        if (isSet('use', data) and isSet('quantity', data['use'])):
            sheet.write(electricityUtilityRow, 6, Decimal(data['use']['quantity']))

        if (isSet('demandKw', data)):
            sheet.write(electricityUtilityRow, 7, Decimal(data['demandKw']))

        if (isSet('costDelivery', data)):
            sheet.write(electricityUtilityRow, 8, Decimal(data['costDelivery']))

        if (isSet('costSupply', data)):
            sheet.write(electricityUtilityRow, 9, Decimal(data['costSupply']))

        if (isSet('costSalesTax', data)):
            sheet.write(electricityUtilityRow, 10, Decimal(data['costSalesTax']))

        if (isSet('costOther', data) and isSet('total', data['costOther'])):
            sheet.write(electricityUtilityRow, 11, Decimal(data['costOther']['total']))

        if (isSet('toPay', data)):
            sheet.write(electricityUtilityRow,13, Decimal(data['toPay']))

        if (isSet('latePaymentCharges', data)):
            sheet.write(electricityUtilityRow, 14, Decimal(data['latePaymentCharges']))

        if (isSet('latePaymentCredits', data)):
            sheet.write(electricityUtilityRow, 15, Decimal(data['latePaymentCredits']))

        if (isSet('notes', data)):
            sheet.write(electricityUtilityRow, 16, data['notes'])

        # skip date pay report column
        electricityUtilityRow += 1
    except Exception, err:
      sys.stderr.write('error electricity utility sheet: ' + str(err) + str(data))


##
# Electricity Supply
def outputToElectricitySupplySheet(data):
    global workbook, electricitySupplyRow
    try:
        sheet = workbook.get_sheet(COMP_SUPPLY_ELECTRIC_SHEET_INDEX)
        if (isSet('accountNumber', data)):
            sheet.write(electricitySupplyRow, 0, data['accountNumber'])
        if (isSet('meterNumber', data)):
            sheet.write(electricitySupplyRow, 1, data['meterNumber'])

        if (isSet('fromDate', data)):
            sheet.write(electricitySupplyRow, 2, data['fromDate'])

        if (isSet('toDate', data)):
            sheet.write(electricitySupplyRow, 3, data['toDate'])

        if (isSet('days', data)):
            sheet.write(electricitySupplyRow, 4, Decimal(data['days']))
        if (isSet('use', data) and isSet('quantity', data['use'])):
            sheet.write(electricitySupplyRow, 5, Decimal(data['use']['quantity']))
        if (isSet('use', data) and isSet('unitPrice', data['use'])):
            sheet.write(electricitySupplyRow, 6, Decimal(data['use']['unitPrice']))

        if (isSet('costSupply', data)):
            sheet.write(electricitySupplyRow, 7, Decimal(data['costSupply']))

        if (isSet('costSalesTax', data)):
            sheet.write(electricitySupplyRow, 8, Decimal(data['costSalesTax']))

        if (isSet('costOther', data) and isSet('total', data['costOther'])):
            sheet.write(electricitySupplyRow, 9, Decimal(data['costOther']['total']))

        if (isSet('toPay', data)):
            sheet.write(electricitySupplyRow, 10, Decimal(data['toPay']))

        if (isSet('latePaymentCharges', data)):
            sheet.write(electricitySupplyRow, 11, Decimal(data['latePaymentCharges']))

        if (isSet('latePaymentCredits', data)):
            sheet.write(electricitySupplyRow, 12, Decimal(data['latePaymentCredits']))


        if (isSet('notes', data)):
            sheet.write(electricitySupplyRow, 13, data['notes'])

        electricitySupplyRow += 1

    except Exception, err:
      sys.stderr.write('error outputing to electricity competitive supply sheet: ' + str(err))

def outputToNaturalGasUtilitySheet(data):
    global workbook, naturalGasUtilityRow
    try:
        sheet = workbook.get_sheet(STD_OFFER_NATURAL_GAS_SHEET_INDEX)
        if (isSet('accountNumber', data)):
            sheet.write(naturalGasUtilityRow, 0, data['accountNumber'])

        if (isSet('meterNumber', data)):
            sheet.write(naturalGasUtilityRow, 1, data['meterNumber'])


        if (isSet('fromDate', data)):
            sheet.write(naturalGasUtilityRow, 2, data['fromDate'])

        if (isSet('toDate', data)):
            sheet.write(naturalGasUtilityRow, 3, data['toDate'])

        if (isSet('days', data)):
            sheet.write(naturalGasUtilityRow, 4, Decimal(data['days']))


        if (isSet('readType', data)):
            sheet.write(naturalGasUtilityRow, 5, data['readType'])

        # Usage CCF not implemented
        # if (isSet('usageCCF', data)):
        #     sheet.write(naturalGasUtilityRow, 6, data['usageCCF'])

        if (isSet('use', data) and isSet('quantity', data['use'])):
            sheet.write(naturalGasUtilityRow, 7, Decimal(data['use']['quantity']))

        if (isSet('costSupply', data)):
            sheet.write(naturalGasUtilityRow, 8, Decimal(data['costSupply']))

        if (isSet('costSupplyWithoutSalesTax', data)):
            sheet.write(naturalGasUtilityRow, 9, Decimal(data['costSupplyWithoutSalesTax']))

        if (isSet('costDelivery', data)):
            sheet.write(naturalGasUtilityRow, 10, Decimal(data['costDelivery']))

        # Default supply not implemented
        # if (isSet('defaultSupply', data)):
        #     sheet.write(naturalGasUtilityRow, 11, Decimal(data['defaultSupply']))

        if (isSet('costSalesTax', data)):
            sheet.write(naturalGasUtilityRow, 12, Decimal(data['costSalesTax']))

        if (isSet('costOther', data) and isSet('total', data['costOther'])):
            sheet.write(naturalGasUtilityRow, 13, Decimal(data['costOther']['total']))


        # Previous balance not implemented
        # if (data.get('previousBalance') and data['previousBalance'] != 'null'):
        #     sheet.write(naturalGasUtilityRow, 14, Decimal(data['previousBalance']))

        if (data.get('toPay') and data['toPay'] != 'null'):
            sheet.write(naturalGasUtilityRow, 15, Decimal(data['toPay']))

        if (isSet('latePaymentCharges', data)):
            sheet.write(naturalGasUtilityRow, 16, Decimal(data['latePaymentCharges']))

        if (isSet('latePaymentCredits', data)):
            sheet.write(naturalGasUtilityRow, 17, Decimal(data['latePaymentCredits']))


        if (isSet('notes', data)):
            sheet.write(naturalGasUtilityRow, 18, data['notes'])

        # skip date pay report column
        naturalGasUtilityRow += 1
    except Exception, err:
      sys.stderr.write('error outputing to natural gas utility sheet: ' + str(err))




def outputToNaturalGasSupplySheet(data):
    global workbook, naturalGasSupplyRow
    try:
        sheet = workbook.get_sheet(COMP_SUPPLY_NATURAL_GAS_SHEET_INDEX)
        if (isSet('accountNumber', data)):
            sheet.write(naturalGasSupplyRow, 0, data['accountNumber'])

        if (isSet('fromDate', data)):
            sheet.write(naturalGasSupplyRow, 1, data['fromDate'])

        if (isSet('toDate', data)):
            sheet.write(naturalGasSupplyRow, 2, data['toDate'])

        if (isSet('days', data)):
            sheet.write(naturalGasSupplyRow, 3, Decimal(data['days']))

        if (isSet('use', data) and isSet('quantity', data['use'])):
            sheet.write(naturalGasSupplyRow, 4, Decimal(data['use']['quantity']))
        if (isSet('use', data) and isSet('unitPrice', data['use'])):
            sheet.write(naturalGasSupplyRow, 5, Decimal(data['use']['unitPrice']))

        if (isSet('costSupply', data)):
            sheet.write(naturalGasSupplyRow, 6, Decimal(data['costSupply']))

        if (isSet('costSalesTax', data)):
            sheet.write(naturalGasSupplyRow, 7, Decimal(data['costSalesTax']))

        if (isSet('costOther', data) and isSet('total', data['costOther'])):
            sheet.write(naturalGasSupplyRow, 8, Decimal(data['costOther']['total']))
        if (isSet('toPay', data)):
            sheet.write(naturalGasSupplyRow, 9, Decimal(data['toPay']))
        if (isSet('latePaymentCharges', data)):
            sheet.write(naturalGasSupplyRow, 10, Decimal(data['latePaymentCharges']))

        if (isSet('latePaymentCredits', data)):
            sheet.write(naturalGasSupplyRow, 11, Decimal(data['latePaymentCredits']))


        if (isSet('notes', data)):
            sheet.write(naturalGasSupplyRow, 12, Decimal(data['notes']))

        if (isSet('billNumberPrinted', data) and data['billNumberPrinted'] and isSet('billNumber', data)):
            sheet.write(naturalGasSupplyRow, 13, data['billNumber'])

    except Exception, err:
      sys.stderr.write('error outputing to natural gas supply sheet: ' + str(err) + str(data))
      raise err

    # skip date pay report column
    naturalGasSupplyRow += 1

try:
    main()
except Exception, e:
    exc_type, exc_value, exc_tb = sys.exc_info()
    traceback.print_exception(exc_type, exc_value, exc_tb)
    # traceback.print_exc(file=sys.stderr)
    # sys.stderr.write(str(e))
    # raise e
