#!/usr/bin/env python

from mixcoatl.admin.billing_code import BillingCode
from mixcoatl import utils
from prettytable import PrettyTable
import argparse
import time
import sys
import os

if __name__ == '__main__':
    """ Returns a list of billingcode codes. """
    start = time.time()
    parser = argparse.ArgumentParser()
    group_two = parser.add_mutually_exclusive_group()
    group_two.add_argument('--json', action='store_true', help='print API response in JSON format.')
    group_two.add_argument('--xml', action='store_true', help='print API response in XML format.')
    group_two.add_argument('--csv', action='store_true', help='print API response in CSV format.')
    cmd_args = parser.parse_args()

    results = BillingCode.all()

    if cmd_args.xml is True or cmd_args.json is True or cmd_args.csv is True:
        if cmd_args.xml is True:
            payload_format = "xml"
        elif cmd_args.csv is True:
            payload_format = "csv"
        else:
            payload_format = "json"

        print utils.print_format(results, payload_format)
    else:
        table = PrettyTable(["ID", "Name", "Budget Code", "Soft Quota", "Hard Quota",
                            "Current Usage", "Projected Usage", "Status"])
        for r in results:
            if hasattr(r, 'soft_quota'):
                soft_quota = r.soft_quota
            else:
                soft_quota = {'currency': '', 'value': 0}
            if hasattr(r, 'hard_quota'):
                hard_quota = r.hard_quota
            else:
                hard_quota = {'currency': '', 'value': 0}
            if hasattr(r, 'current_usage'):
                current_usage = r.current_usage
            else:
                current_usage = {'currency': '', 'value': 0}

            table.add_row([r.billing_code_id, r.name, r.finance_code,
                           "%s %.2f" % (soft_quota['currency'], soft_quota['value']),
                           "%s %.2f" % (hard_quota['currency'], hard_quota['value']),
                           "%s %.2f" % (current_usage['currency'], current_usage['value']),
                           "%s %.2f" % (r.projected_usage['currency'],
                           r.projected_usage['value']), r.status])
        table.align = 'l'
        print(table)

    if 'DCM_DEBUG' in os.environ:
        print 'Results returned in', time.time()-start, 'seconds.'
