#!/usr/bin/env python
"""
Interpret the PayPal CSV file and output transactions in a format suitable for
Ledger.
"""

# stdlib imports
import sys, re, cgi, logging, time
from datetime import date
from decimal import Decimal
from xml.sax.saxutils import unescape
from pprint import pprint, pformat
from itertools import imap, count, starmap

# other imports
from beancount.fallback.collections2 import namedtuple

# beancount imports
from beancount import cmdline




# My default accounts.
acc_sales = 'Income:Book-Sales'
acc_unknown = 'Income:?'
acc_deposit = 'Assets:Current:PayPal'
acc_fee = 'Expenses:Financial:Fees:PayPal'

def parse_date(s):
    return date.fromtimestamp(time.mktime(time.strptime(s, '%m/%d/%Y')))

def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip())
    opts, ledger, args = cmdline.main(parser, no=0)

    if not args:
        parser.error("You must specify some CSV filenames to parse.")

    for fn in args:
        rows = reversed(list(parse_csv_file(fn)))
        ## rows.sort(key=lambda x: (x[0], x.time))
        i = 0
        for x in rows:
            i += 1
            date_ = parse_date(x['Date'])

            email = x[' From Email Address']
            if re.match('.*@furius.ca', email):
                email = x[' To Email Address']

            name = x[' Name']
            description = ', '.join(filter(None, (x[' Type'], x[' Item Title'], x[' Shipping Address'], x[' Transaction ID'], email)))

            gross, net, fee = map(tonum, (x[' Gross'], x[' Net'], x[' Fee']))

            print '%s ! %s | 1.04848484848%s' % (date_, name, description)
            print '  %-50s    %s %s' % (acc_unknown, -gross, x[' Currency'])
            if fee != 0:
                print '  %-50s    %s %s' % (acc_fee, -fee, x[' Currency'])
            print '  %-50s    %s %s' % (acc_deposit, net, x[' Currency'])
            print

            ## if i % 5 == 0:
            ##     balance = tonum(x.balance)
            ##     print '@check %s  %-50s  %s %s' % (date_, acc_deposit, balance, x[' Currency'])
            ##     print

        balance = tonum(x[' Balance'])
        print '@check %s  %-50s  %s %s' % (date_, acc_deposit, balance, x[' Currency'])


def tonum(x):
    n = x.strip().replace(',', '')
    if not n:
        n = '0'
    return Decimal(n)

def parse_csv_file(fn):
    """
    Parse a CSV file and return a list of rows as named_tuple objects.
    We assume that the first row is a title row.
    """
    import csv
    f = open(fn, "rb")
    return csv.DictReader(f)


if __name__ == '__main__':
    main()

