import flask
from flask import request

import commands.loader as command_loader
from commands.command_base import AbstractCommand

import os
import praxis_logging
praxis_logger_obj = praxis_logging.praxis_logger()
praxis_logger_obj.init(os.path.basename(__file__))
praxis_logger_obj.log("\n -Starting Logs: " + os.path.basename(__file__))

api = flask.Flask(__name__)
# enable/disable this to get web pages of crashes returned
api.config["DEBUG"] = False

loadedCommands = {}

def init():
    # todo load entire command library and cache it here
    load_commands()


def load_commands():
    global loadedCommands
    loadedCommands = command_loader.load_commands(AbstractCommand.CommandType.Ver2)


def is_command(command: str) -> bool:
    #print(command)
    for cmd in loadedCommands:
        #print(cmd)
        if command == cmd:
            return True

    if command == "!echo":
        return True
    else:
        return False

def handle_command(source, username, command, rest, bonusData):
    if command == "!echo":
        message = "Got payload [%s]" % rest
        #print(message)
        return flask.make_response("{\"message\":\"%s\"}" % message, 200, {"Content-Type": "application/json"})

    tempSource = source.replace('CommandSource.', '')
    realSource = AbstractCommand.CommandSource.__dict__[tempSource]
    cmd:AbstractCommand = loadedCommands[command]
    if cmd is not None:
        cmd_response = cmd.do_command(source, username, command, rest, bonusData)
        return flask.make_response("{\"message\":\"%s\"}" % cmd_response, 200, {"Content-Type": "application/json"})

    #print("Doing a command")


@api.route('/api/v1/command', methods=['GET'])
def command_check():
    if 'name' in request.args:
        if is_command(request.args['name']):
            return flask.make_response('', 200)
        else:
            return flask.make_response('', 404)


@api.route('/api/v1/exec_command', methods=['GET'])
def exec_command():
    if 'command_name' not in request.args:
        return flask.make_response('{\"text\":"Argument \'command_name\' not in request"}', 400)
    if 'rest' not in request.args:
        return flask.make_response('{\"text\":"Argument \'rest\' not in request"}', 400)

    if 'command_source' not in request.args:
        return flask.make_response('{\"text\":"Argument \'command_source\' not in request"}', 400)

    if 'user_name' not in request.args:
        username = "User"
    else:
        username = request.args['user_name']

    return handle_command(request.args['command_source'], username, request.args['command_name'], request.args['rest'], request.args['bonus_data'])


if __name__ == '__main__':
    init()
    api.run(host='0.0.0.0', port=42010)
