#!/usr/bin/env python3

import sys
import os
import argparse
import asyncio
import importlib
rootdir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.append(rootdir)

from robotjes.client import config
from robotjes import client, Timer



class PlayerClient:

    def __init__(self):
        pass

    def robo_status(self, game_tick, robo_id, robo_status):
        pass

    def issue_command(self, game_tick, robo_id, cmd, reply):
        print(f"command: {game_tick}/{robo_id}/{cmd}/{reply}")


def load_client(module_name):
    # load user module that should contain a function like: def execute(robo)
    execute_entrypoint = None
    try:
        module = importlib.import_module(module_name)
        if hasattr(module, 'execute'):
            execute_entrypoint = module.execute
    except Exception as e:
        print(f"failure to load user module: {str(e)}")
        exit(1)
    return execute_entrypoint


async def main(args, script, loop):
    clnt = PlayerClient()
    rest_client = client.RestClient(loop, args.url)
    handler = client.RemoteEngineHandler(rest_client, args.player, args.name, args.password)
    player = client.Player(handler, loop, clnt)
    timer = Timer(1, player.timer, True)
    await player.start_player(script)
    success = await player.run_game()
    timer.cancel()


if __name__ == "__main__":
    # get commandline arguments
    parser = argparse.ArgumentParser(description='CommandLineInterface (CLI) for Player')
    parser.add_argument('--url', type=str, default=config.REST_URL, help='url of the robotjes REST entrypoint')
    parser.add_argument('--player', type=str, default="me", help='name or id of the umpire')
    parser.add_argument('--name', type=str, default="game1", help='name of the game to join')
    parser.add_argument('--password', type=str, default="secret1", help='password needed to enter the game')
    parser.add_argument('--module', type=str, default="sample.player.player104", help='module containing the player logic')
    args = parser.parse_args()

    script = load_client(args.module)

    if script:
        aloop = asyncio.get_event_loop()
        aloop.run_until_complete(main(args, script, aloop))
        aloop.stop()
    else:
        print(f"no valid user module: {args.module if args.module else 'ABSENT'}")
