#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2017-2019 Xavier G. <xavier.boobank@kindwolf.org>
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See the COPYING file for more details.
"""
boobank-accounts takes one or several JSON files, as created by boobank-cacher
when running and caching a "boobank list" command, and display their contents.
"""

import time
import argparse
from prettytable import PrettyTable
from termcolor import colored
from boobank_utils import format_amount, format_timestamp_colored, load_json
from boobank_utils import DEFAULT_CURRENCY, COLORING_THRESHOLD, MAX_AGE

def parse_args():
    """
    Parse command-line arguments.
    """
    description = 'Display the contents of cached "boobank list" JSON files.'
    args_parser = argparse.ArgumentParser(description=description)
    args_parser.add_argument('json_file', nargs='*', default=['-'], help='JSON files to display')
    return args_parser.parse_args()

def main():
    """
    Main function.
    """
    args = parse_args()
    table = get_table()
    total = 0
    filepaths = set(args.json_file)
    for filepath in filepaths:
        accounts = load_json(filepath)
        timestamp = accounts.get('timestamp', time.time())
        for account in accounts.get('data', []):
            add_account(table, account, timestamp)
            total += float(account.get('balance'))
    print(table)
    total_line = '%-60s' % ''
    total_line += colored('Total: ', 'white', attrs=['bold'])
    total_line += format_amount(total, DEFAULT_CURRENCY, COLORING_THRESHOLD)
    print(total_line)

def get_table():
    """
    Create and return the PrettyTable instance used to display data.
    """
    ptable = PrettyTable()
    ptable.field_names = ['Account ID', 'Account name', 'Balance', 'Data cached on']
    ptable.field_names = [colored(x, 'white', attrs=['bold']) for x in ptable.field_names]
    ptable.align = 'r'
    ptable.align[ptable.field_names[1]] = 'l'
    ptable.align[ptable.field_names[3]] = 'c'
    return ptable

def add_account(table, account, cache_timestamp):
    """
    Add the given bank account to the given PrettyTable instance.
    """
    account_id = colored(account.get('id'), 'cyan')
    label = colored(account.get('label'), 'cyan')
    currency = account.get('currency', DEFAULT_CURRENCY)
    balance = format_amount(float(account['balance']), currency, COLORING_THRESHOLD)
    cache_date = format_timestamp_colored(cache_timestamp, MAX_AGE)
    table.add_row([account_id, label, balance, cache_date])

if __name__ == '__main__':
    main()