#!/usr/bin/env python3

import sys
import os
import asyncio
import argparse
import importlib

from robotjes.sim import Mazes
from robotjes import client, Timer
from robotjes.sim import Engine, Map

rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
mazepath = os.path.join(rootpath, "sample/mazes")
sys.path.append(rootpath)

class Player_Client:

    def __init__(self):
        pass

    def create_robo(self, game_tick, robo_id):
        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}")


async def main(script, engine, loop):
    clnt = Player_Client()
    handler = client.LocalEngineHandler(engine)
    player = client.Player(handler, loop, clnt)
    timer = Timer(1, player.timer, True)
    await player.start_player(script)
    success = await player.run_game()
    timer.cancel()


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


def load_simulation(maze_name):
    mazes = Mazes(mazepath)
    mapstr = mazes.get_map(maze_name)
    map = Map.fromstring(mapstr)
    engine = Engine(map)
    return engine


if __name__ == "__main__":
    # get commandline arguments
    parser = argparse.ArgumentParser(description='Execute a Robomind Academy Python script.')
    parser.add_argument('--maze', type=str, default="default", help='name of the maze to use')
    parser.add_argument('--module', type=str, default="sample.player.player103", help='module containing the player logic')
    args = parser.parse_args()

    script = load_client(args.module)
    engine = load_simulation(args.maze)

    if script and engine:
        aloop = asyncio.get_event_loop()
        aloop.run_until_complete(main(script, engine, aloop))
        aloop.stop()
    else:
        print(f"Need valid script and maze in order to run")
