#!/usr/bin/env python

# lt-transact - enter new transactions into Ledger files
# Copyright (C) 2011 Fraser Tweedale
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import datetime
import sys

import ltlib.config
import ltlib.ui
import ltlib.xn


# parse args

parser = argparse.ArgumentParser(
    description="Ask for details of cash transaction and write to ledger"
)
parser.add_argument(
    '--account',
    default='Expenses:Cash',
    help="the account to which the given transactions pertain"
)
parser.add_argument(
    '--out',
    dest='outfile',
    type=argparse.FileType('a'),
    help="the Ledger transaction output file (will be appended to)"
)
args = parser.parse_args()

# get a user interface
uio = ltlib.ui.UI()

# we must have an outfile or an outpat
if not args.outfile:
    outpat = ltlib.config.outpat(args.account)
    if not outpat:
        uio.show('BAIL OUT: No outfile or outpat provided')
        sys.exit(1)

try:
    # ask the date
    xn_dict = {
        'date': uio.pastdate("Enter date", datetime.date.today()),
        'desc': uio.text("Enter description"),
        'src': [ltlib.xn.Endpoint(
            uio.account("Enter source account", "Expenses:Cash"),
            -uio.decimal("Enter transaction amount")
        )],
        'dst': []
    }
    xn_dict['amount'] = -xn_dict['src'][0].amount

    # ask the destination endpoint(s)
    uio.show('\n')
    uio.show('Enter destination endpoints:')
    remaining = xn_dict['amount']
    while remaining:
        uio.show('\n${} remaining'.format(remaining))
        account = uio.account(' Enter account')
        amount = uio.decimal(
            ' Enter amount',
            default=remaining,
            lower=0,
            upper=remaining
        )
        xn_dict['dst'].append(ltlib.xn.Endpoint(account, amount))
        remaining = xn_dict['amount'] - sum(map(lambda x: x.amount, xn_dict['dst']))

    # write transaction to ledger
    xn = ltlib.xn.Xn(**xn_dict)
    uio.show('')
    uio.show(xn.summary())
    if args.outfile:
        print >> args.outfile, xn.ledger()
    else:
        with open(ltlib.config.format_outpat(outpat, xn), 'a') as f:
            print >> f, xn.ledger()
    uio.show('Wrote ledger.')

except ltlib.ui.RejectWarning:
    # bail out
    uio.show('')
    uio.show('BAIL OUT')
    sys.exit(1)
