import getpass
import inspect
import sys
import client
import connection
from client import allowed_commands
from connection import client_request


def login(username=None, password=None):
    if connection.session_id is not None:
        client.fake_loading_bar('Signing out', delay=0.025)
        connection.session_id = None

    if username is None:
        username = input('Username: ')

    if password is None:
        if sys.stdin.isatty():
            password = getpass.getpass('Password: ')
        else:
            password = input('Password: ')

    response = client_request('login', {"username": username, "password": password})
    success = 'session_id' in response
    if success:
        connection.session_id = response['session_id']
        print('Login successful.')
    else:
        if 'error_message' in response:
            print('Login failed with message:', response['error_message'])
        else:
            print('Login failed.')


def register(username=None, password=None, game_key=None):
    if connection.session_id is not None:
        client.fake_loading_bar('Signing out', delay=0.025)
        connection.session_id = None

    if username is None:
        username = input('Username: ')

    if password is None:
        if sys.stdin.isatty():
            password = getpass.getpass('Password: ')
        else:
            password = input('Password: ')

    if game_key is None:
        print('Entering a game key will provide you with some starting money and other useful stuff.')
        game_key = input('Game key (leave empty if you don\'t have one): ')

    response = client_request('register', {"username": username, "password": password, "game_key": game_key})

    if 'error_message' in response:
        print('Registration failed with message:', response['error_message'])


# noinspection PyShadowingBuiltins
def help():
    print('Allowed commands:')
    for cmd in allowed_commands:
        this_module = sys.modules[__name__]
        method = getattr(this_module, cmd)
        params = inspect.signature(method).parameters
        num_args = len(params)
        if num_args > 0:
            print('`' + cmd + '`', 'takes the following', num_args, 'arguments:')
            for p in params:
                print(' -', p)  # TODO print default value
        else:
            print('`' + cmd + '`', 'takes no arguments')