#!/usr/bin/env python
"""Get loyalty details from TouchBistro.

Usage:
    loyalty [options] report <db_path> <earliest_date> [<latest_date>]

Options:

 -d, --debug    Print detailed debug logging
 -j, --json     Output a JSON summary for the order
 -c, --csv      Output as CSV
 -f, --file=F   Specify an output file instead of stdout
 --day-boundary=X  Specify a day boundary time [default: 02:00:00]

If <latest_date> is omitted, it is assumed to be the same as earliest
date (for a one-day report).

"""
import os
import sys
import logging
from docopt import docopt
from touchbistro.reports import loyalty_report, write_utf8_bom


if __name__ == '__main__':
    ARGS = docopt(__doc__, version='loyalty 0.1')
    logging.basicConfig()

    if ARGS.get('--debug', False):
        print(ARGS, file=sys.stderr)
        logging.getLogger().setLevel(logging.DEBUG)

    if not ARGS.get('<latest_date>'):
        ARGS['<latest_date>'] = ARGS['<earliest_date>']

    if ARGS.get('--file'):
        with open(
                os.path.expanduser(ARGS.get('--file')), 'w',
                encoding='utf-8') as outfile:
            write_utf8_bom(outfile)
            loyalty_report(
                ARGS.get('<db_path>'),
                ARGS.get('<earliest_date>'),
                ARGS.get('<latest_date>', ARGS.get('<earliest_date>')),
                ARGS.get('--day-boundary'),
                outfile,
                in_csv=ARGS.get('--csv'),
                in_json=ARGS.get('--json'))
    else:
        loyalty_report(
            ARGS.get('<db_path>'),
            ARGS.get('<earliest_date>'),
            ARGS.get('<latest_date>', ARGS.get('<earliest_date>')),
            ARGS.get('--day-boundary'),
            sys.stdout,
            in_csv=ARGS.get('--csv'),
            in_json=ARGS.get('--json'))
    sys.exit(0)
