#!/usr/bin/env python

import argparse
import requests
import json

def arg_parser(client):
    parser = argparse.ArgumentParser(prog='drk',
                                          usage='%(prog)s [commands]',
                                          description="""DarkFi wallet
                                          command-line tool""")
    #subparser = parser.add_subparsers(help='All available commands', title="Commands", dest='cmd')
    #subparser.metavar = 'subcommands';
    #login = subparser.add_parser('login', help='wallet login')
    ##test = subparser.add_parser('test', help='test wallet functions')
    #new = subparser.add_parser('new', help='create something new')

    #new.add_argument('-w', '--wallet', action='store_true', help='Create a new wallet')
    #new.add_argument('-k', '--key', action='store_true', help='Create a new key')
    #new.add_argument('-c', '--cashier', action='store_true', help='Create a cashier wallet')

    #login.add_argument('-u', '--username', type=str, required=True)
    #login.add_argument('-p', '--password', type=str, required=True)

    ##test.add_argument('-k', '--key', dest='key', action='store_true', help='Test key')
    ##test.add_argument('-p', '--path', dest='path', action='store_true', help='Test path')
    ##test.add_argument('-pk', '--pkey', dest='pkey', action='store_true', help='Print test key')
    ##test.add_argument('-ck', '--ckey', dest='ckey', action='store_true', help='Cashier test key')
    ##test.add_argument('-w', '--wallet', dest='wallet', action='store_true', help='Create a new wallet')
    ##test.add_argument('-c', '--cashier', dest='cashier',action='store_true', help='Create a cashier wallet')

    parser.add_argument('-c', '--cashier', action='store_true', help='Create a cashier wallet')
    parser.add_argument('-w', '--wallet', action='store_true', help='Create a new wallet')
    parser.add_argument('-k', '--key', action='store_true', help='Test key')
    parser.add_argument('-i', '--info', action='store_true', help='Request info from daemon')
    parser.add_argument('-hi', '--hello', action='store_true', help='Test hello')
    parser.add_argument("-s", "--stop", action='store_true', help="Send a stop signal to the daemon")
    args = parser.parse_args()

    #if args.path:
    #    try:
    #        print("Testing path...")
    #        client.test_path(client.payload)
    #    except Exception:
    #        raise

    #if args.pkey:
    #    try:
    #        print("Attempting to print cashier key...")
    #        client.cashkey(client.payload)
    #    except Exception:
    #        raise

    if args.key:
        try:
            print("Attemping to generate a create key pair...")
            client.key_gen(client.payload)
        except Exception:
            raise

    if args.wallet:
        try:
            print("Attemping to generate a create wallet...")
            client.create_wallet(client.payload)
        except Exception:
            raise

    if args.info:
        try:
            print("Info was entered")
            client.get_info(client.payload)
            print("Requesting daemon info...")
        except Exception:
            raise

    if args.stop:
        try:
            print("Stop was entered")
            client.stop(client.payload)
            print("Sending a stop signal...")
        except Exception:
            raise

    if args.hello:
        try:
            print("Hello was entered")
            client.say_hello(client.payload)
        except Exception:
            raise

    if args.cashier:
        try:
            print("Cash was entered")
            client.create_cashier_wallet(client.payload)
        except Exception:
            raise

# TODO: refactor into async
class DarkClient:
    # TODO: generate random ID (4 byte unsigned int) (rand range 0 - max size
    # uint32
    def __init__(self):
        self.url = "http://localhost:8000/"
        self.payload = {
            "method": [],
            "params": [],
            "jsonrpc": [],
            "id": [],
        }

    #def ckeygen(self, payload):
    #    payload['method'] = "cash_key_gen"
    #    payload['jsonrpc'] = "2.0"
    #    payload['id'] = "0"
    #    ckeygen = self.__request(payload)
    #    print(ckeygen)

    #def cashkey(self, payload):
    #    payload['method'] = "get_cash_key"
    #    payload['jsonrpc'] = "2.0"
    #    payload['id'] = "0"
    #    cashk = self.__request(payload)
    #    print(cashk)
    #    
    #def test_path(self, payload):
    #    payload['method'] = "test_path"
    #    payload['jsonrpc'] = "2.0"
    #    payload['id'] = "0"
    #    test = self.__request(payload)
    #    print(test)
        
    def key_gen(self, payload):
        payload['method'] = "key_gen"
        payload['jsonrpc'] = "2.0"
        payload['id'] = "0"
        key = self.__request(payload)
        print(key)

    def get_info(self, payload):
        payload['method'] = "get_info"
        payload['jsonrpc'] = "2.0"
        payload['id'] = "0"
        info = self.__request(payload)
        print(info)

    def stop(self, payload):
        payload['method'] = "stop"
        payload['jsonrpc'] = "2.0"
        payload['id'] = "0"
        stop = self.__request(payload)
        print(stop)

    def say_hello(self, payload):
        payload['method'] = "say_hello"
        payload['jsonrpc'] = "2.0"
        payload['id'] = "0"
        hello = self.__request(payload)
        print(hello)
    
    def create_wallet(self, payload):
        payload['method'] = "create_wallet"
        payload['jsonrpc'] = "2.0"
        payload['id'] = "0"
        wallet = self.__request(payload)
        print(wallet)

    def create_cashier_wallet(self, payload):
        payload['method'] = "create_cashier_wallet"
        payload['jsonrpc'] = "2.0"
        payload['id'] = "0"
        wallet = self.__request(payload)
        print(wallet)


    def __request(self, payload):
        response = requests.post(self.url, json=payload).json()
        # print something better
        # parse into data structure 
        print(response)
        assert response["jsonrpc"]

    
if __name__ == "__main__":
    client = DarkClient()
    arg_parser(client)

    #rpc()
    ## Example echo method
    #payload = {
    #    #"method:": args,
    #    #"method": "stop",
    #    "method": "get_info",
    #    #"method": "say_hello",
    #    #"params": [],
    #    "jsonrpc": "2.0",
    #    "id": 0,
    #}
    #response = requests.post(url, json=payload).json()

    #print(response)
    #assert response["result"] == "Hello World!"
    #assert response["jsonrpc"]
