#!/usr/bin/env python
'''
@license: GNU Lesser General Public License v3.0 (see LICENSE)
'''

from csb43.utils import DECIMAL
import csb43.ofx as ofx
import csb43.csb43 as csb_43

import argparse
import sys


def get_options():

    parser = argparse.ArgumentParser(description="""Convert a CSB43 file to a
                                                    OFX file""")
    parser.add_argument('csbFile', nargs='?',
                        type=argparse.FileType('rU'),
                        default=sys.stdin,
                        help="a csb43 file (stdin by default)")
    parser.add_argument('ofxFile', nargs='?',
                        type=argparse.FileType('w'),
                        default=sys.stdout,
                        help="name for output file (stdout by default)")
    parser.add_argument('-s', '--strict', dest='strict',
                        action='store_true',
                        default=False, help='strict mode')
    parser.add_argument('-df', '--dayfirst', dest="yearFirst",
                        action='store_false', default=True,
                        help="""use DDMMYY as date format while parsing
                        the csb43 file instead of YYMMDD""")
    parser.add_argument('-d', '--decimal', dest="decimal", type=int,
                        default=DECIMAL,
                        help="""set the number of decimal places for the
                        currency type (default: %d)""" % DECIMAL)

    return parser.parse_args()


if __name__ == '__main__':

    try:
        args = get_options()

        csb = csb_43.File(args.csbFile, strict=args.strict,
                    decimal=args.decimal, yearFirst=args.yearFirst)

        print >> sys.stderr, "*", "File:", args.csbFile.name

        csb_43.showInfo(csb, sys.stderr)

        ofxFile = ofx.convertFromCsb(csb)

        args.ofxFile.write(str(ofxFile))
        args.ofxFile.write('\n')

    except Exception, e:
        print >> sys.stderr, e
