#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    Registrar
    ~~~~~
    :copyright: (c) 2014-2016 by Halfmoon Labs, Inc.
    :copyright: (c) 2016 blockstack.org
    :license: MIT, see LICENSE for more details.
"""

import sys
import os

from time import sleep

# Hack around absolute paths
current_dir = os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
sys.path.insert(0, parent_dir)

from registrar.utils import pretty_print as pprint
from registrar.utils import config_log

from registrar.drivers import WebappDriver, APIDriver

from registrar.config import SLEEP_INTERVAL, RATE_LIMIT
from registrar.config import DEFAULT_WALLET_DISPLAY, DEFAULT_WALLET_OFFSET

from registrar.queue import display_queue_info
from registrar.queue import cleanup_transfer_queue, cleanup_update_queue
from registrar.queue import cleanup_register_queue, cleanup_preorder_queue

from registrar.wallet import wallet, display_wallet_info, refill_wallet

from registrar.blockchain import get_block_height

log = config_log(__name__)


def usage():

    log.info("Options are register, update, clean, stats, reprocess")


def run_cli(command, argv=None):

    # currently configured for the following drivers
    webapp_data = WebappDriver()
    api_data = APIDriver()

    if command == "preorder":
        api_data.process_new_users(nameop='preorder')
        webapp_data.process_new_users(nameop='preorder')

    elif command == "register":
        api_data.process_new_users(nameop='register')
        webapp_data.process_new_users(nameop='register')

    elif command == "update":
        api_data.process_new_users(nameop='update')
        webapp_data.update_users()
        webapp_data.process_new_users(nameop='update')

    elif command == "transfer":
        api_data.process_new_users(nameop='transfer')
        webapp_data.transfer_users()
        webapp_data.process_new_users(nameop='transfer')

    elif command == "clean":

        cleanup_rejected = False

        try:
            queue = argv[2]
        except:
            queue = "all"

        try:
            rejected = argv[3]

            if rejected == "rejected":
                cleanup_rejected = True
        except:
            pass

        if queue == "transfer":
            cleanup_transfer_queue()
        elif queue == "update":
            cleanup_update_queue()
        elif queue == "register":
            cleanup_register_queue(cleanup_rejected)
        elif queue == "preorder":
            cleanup_preorder_queue(cleanup_rejected)
        elif queue == "all":
            cleanup_transfer_queue()
            cleanup_update_queue()
            cleanup_register_queue(cleanup_rejected)
            cleanup_preorder_queue(cleanup_rejected)

    elif command == "status":

        webapp_data.display_stats()
        api_data.display_stats()
        log.debug('-' * 5)

        display_details = False
        try:
            cmd = argv[2]

            if cmd == "details":
                display_details = True
        except:
            pass
        display_queue_info(display_details)

    elif command == "blocks":
        log.info("Block height: %s" % get_block_height())

    elif command == "wallet":

        count = DEFAULT_WALLET_DISPLAY
        offset = DEFAULT_WALLET_OFFSET
        display_only = True

        try:
            count = int(argv[2])
            offset = int(argv[3])
        except:
            pass

        try:
            cmd = argv[4]

            if cmd == "refill":
                live = False

                try:
                    live_command = argv[5]
                    if live_command == "live":
                        live = True
                except:
                    pass

                display_only = False
                refill_wallet(count=count, offset=offset, live=live)

        except Exception as e:
            pass

        if display_only:
            active_addresses = wallet.get_child_keypairs(count=count, offset=offset)
            display_wallet_info(active_addresses)

    elif command == "test":

        # commands for testing go here
        webapp_data.update_users()

    elif command == "reprocess":

        try:
            username = argv[2]
        except:

            fname = 'processing.txt'
            with open(fname) as f:
                content = f.readlines()

            for username in content:
                username = username.rstrip('\n')
                webapp_data.reprocess_user(username)
                webapp_data.update_users(reprocess_username=username)
        else:
            webapp_data.reprocess_user(username)
            webapp_data.update_users(reprocess_username=username)
    else:
        usage()


def run_loop():

    current_block = get_block_height()
    last_block = current_block - 1

    while(1):

        log.debug("At block: %s" % current_block)

        if last_block == current_block:
            log.debug("No new blocks. Sleeping")
            sleep(SLEEP_INTERVAL)
            current_block = get_block_height()
        else:
            # empty queues in reverse
            run_cli('reprocess')
            run_cli('transfer')
            run_cli('update')
            run_cli('register')
            run_cli('preorder')
            #except Exception as e:
            #    log.debug(e)
            #else:
            last_block = current_block

if __name__ == '__main__':

    try:
        command = sys.argv[1]
    except:
        usage()
        exit(0)

    if command == "loop":
        try:
            run_loop()
        except KeyboardInterrupt:
            log.debug("Exiting loop.")
    else:
        run_cli(command, sys.argv)
