# Mattermost Bot module.
#  Copyright (c) 2016-2022 by Someone <someone@somenet.org> (aka. Jan Vales <jan@jvales.net>)
#  published under MIT-License

from inspect import cleandoc

import MCAPI


# pylint: disable=wrong-import-position
from AbstractCommand import AbstractCommand
class CommandDrinkBindAccount(AbstractCommand):
    TRIGGER = "drink-bind-account"
    CONFIG = {"display_name": "somebot-command", "auto_complete": True,
              "auto_complete_hint": "<drink-terminal-username> <drink-terminal-password>",
             }
    USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = AbstractCommand.ICON_PRIVATE+"Bind your drink-terminal-account to your mattermost username."


    def on_POST(self, request, data):
        data['text'] = data['text'].strip()
        mc_credentials = data['text'].split(" ", 2)

        if data["text"] == "" or data["text"].lower() == "help" or len(mc_credentials) != 2:
            request.respond_cmd_err(cleandoc("""This command takes exactly 2 parameters: ``<drink-terminal-username> <drink-terminal-password``.
                Once you passed the correct drink-terminal credentials your Mattermost account will be bound to that account.
                The binding can be undone at the drink-terminal @ fsinf or via debug weg-front-end.
                Once sucessfully bound you will be able to use ``/drink <drink-terminal-input-string>`` to pay for your drink.
                """))

        try:
            handle = MCAPI.API("KEYBOARD", mc_credentials[0], mc_credentials[1])
            handle.manage_token('add', 'MM_'+data["user_id"])
        except MCAPI.APIException as exc:
            if exc.message == 'CERR_AUTH_FAIL_ACCPWDRATE':
                request.respond_cmd_err("Failed to bind Mattermost account to drink-terminal account: Invalid drink-terminal credentials.")
            elif exc.message == 'CERR_FAILED_TO_ADD_TOKEN_EXISTING':
                request.respond_cmd_err("Failed to bind Mattermost account to drink-terminal account: Mattermost username is already bound to an account.")
            else:
                request.respond_cmd_err("Failed to bind Mattermost account to drink-terminal account: Unknown error: "+repr(exc))
            return

        self.bot.debug_chan("``/drink-bind-account success: @"+data["user_name"]+'``')
        request.respond_cmd_temp("## :white_check_mark: Success! :)\n####Sucessfully bound Mattermost account and drink-terminal account :)")
