#!/usr/bin/env python3

import argparse
import datetime

import tabulate
import fastmap

USAGE = """Fastmap CLI for service administration."""

DESCRIPTION = """
Fastmap CLI for service administration.
\n\n
Examples:
$ fastmap accounts

"""

EPILOG = """Run `fastmap <operation> --help` for help on individual operations."""


def _relative_time(seconds):
    seconds = datetime.datetime.utcnow().timestamp() - seconds
    if not seconds:
        return 'never'
    if seconds > 60 * 60 * 24 * 2:
        return '%d days ago' % (seconds // (60 * 60 * 24))
    elif seconds > 60 * 60 * 2:
        return '%d hours ago' % (seconds // (60 * 60))
    elif seconds > 120:
        return '%d minutes ago' % (seconds // 60)
    elif seconds > 2:
        return '%d seconds ago' % seconds
    else:
        return 'just now'


def _prettify(items):
    for item in items:
        item['created'] = _relative_time(item['created'])
        item['updated'] = _relative_time(item['updated'])

        if item.get('idle'):
            item['idle'] = _relative_time(item['idle'])

        if item.get('heartbeat_ts'):
            item['heartbeat_ts'] = _relative_time(item['heartbeat_ts'])
        # task['state'] = task['task_state']
        # task['id'] = task['task_id']

        # del task['last_heartbeat']
        # del task['task_state']
        # del task['task_id']

        # task['progress'] = task['progress'] and "%.1f%%" % task['progress']


def list_accounts(config):
    resp = fastmap.sdk_lib.post_request(
        url=config.cloud_url + '/admin/v1/list_accounts',
        data={},
        secret=config.secret,
        log=fastmap.sdk_lib.FastmapLogger('QUIET'))

    accounts = resp.obj['accounts']
    accounts.sort(key=lambda x: x['created'], reverse=True)
    _prettify(accounts)
    print(tabulate.tabulate(accounts, headers='keys'))


def list_workers(config):
    resp = fastmap.sdk_lib.post_request(
        url=config.cloud_url + '/admin/v1/list_workers',
        data={},
        secret=config.secret,
        log=fastmap.sdk_lib.FastmapLogger('QUIET'))

    workers = resp.obj['workers']
    workers.sort(key=lambda x: x['created'], reverse=True)
    import pprint; pprint.pprint(workers)
    _prettify(workers)
    print(tabulate.tabulate(workers, headers='keys'))


def add_account(config, email, password):
    resp = fastmap.sdk_lib.post_request(
        url=config.cloud_url + '/admin/v1/add_account',
        data={'email': email, 'password': password},
        secret=config.secret,
        log=fastmap.sdk_lib.FastmapLogger('QUIET'))

    account_id = resp.obj['account_id']
    secret_token = resp.obj['secret_token']
    print("New account is %s token=%s" % (account_id, secret_token))


def add_credits(config, account_id, amount):
    # TODO check account_id
    resp = fastmap.sdk_lib.post_request(
        url=config.cloud_url + '/admin/v1/add_credit',
        data={'account_id': account_id, 'amount': amount},
        secret=config.secret,
        log=fastmap.sdk_lib.FastmapLogger('QUIET'))

    print("Added credits. New balance = %.2f" % resp.obj['balance'])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        # usage=DESCRIPTION,
        description=DESCRIPTION,
        epilog=EPILOG,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument(
        "--config",
        help="Location of configuration file generated by depoly_gcp.py. "
             "If omitted, will attempt to use the default configuration. ")

    subparsers = parser.add_subparsers(
        dest='operation', required=True,
        help='sub-command help')

    list_accounts_p = subparsers.add_parser(
        'list_accounts', help="Get account info")

    list_workers_p = subparsers.add_parser(
        'list_workers', help="Get worker info")

    add_credits_p = subparsers.add_parser(
        'add_credits', help="Add credits to users")
    add_credits_p.add_argument(
        "account_id",
        help="Account ID")
    add_credits_p.add_argument(
        "amount",
        help="Amount")

    add_account_p = subparsers.add_parser(
        'add_account', help="Add new account")
    add_account_p.add_argument(
        "email",
        help="Email")
    add_account_p.add_argument(
        "password",
        help="Password")

    args = parser.parse_args()

    config = fastmap.init(config=args.config)

    if config.exec_policy == fastmap.ExecPolicy.LOCAL:
        raise AssertionError("The fastmap CLI does not support a LOCAL exec_policy. "
                             "Check your configuration file.")

    if args.operation == 'list_accounts':
        list_accounts(config)
    if args.operation == 'list_workers':
        list_workers(config)
    if args.operation == 'add_credits':
        add_credits(config, args.account_id, args.amount)
    if args.operation == 'add_account':
        add_account(config, args.email, args.password)
