# 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 re
import datetime

import MCAPI

# pylint: disable=wrong-import-position
from AbstractCommand import AbstractCommand
class CommandDrink(AbstractCommand):
    TRIGGER = "drink"
    CONFIG = {"display_name": "somebot-command", "auto_complete": True,
              "auto_complete_hint": "['help'|<[count]shortcut>]",
             }
    USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = AbstractCommand.ICON_PRIVATE+"Buy a drink."


    def __init__(self, team_id, drink_terminal_user, drink_terminal_pass):
        super().__init__(team_id)

        self.drink_terminal_user = drink_terminal_user
        self.drink_terminal_pass = drink_terminal_pass


    def on_POST(self, request, data, rerun=True):
        try:
            apirequest = {}
            apirequest["act"] = "create_token_secret"
            handle = MCAPI.API("KEYBOARD", self.drink_terminal_user, self.drink_terminal_pass)
            token_secret = handle.api_request(apirequest)
            handle = MCAPI.API("MM", data["user_id"])
            MCAPI.API.token_secret = token_secret["token_secret"]
            account_data = handle.get_account_info()
            msg = ":arrow_right: Available credits:``"+str(account_data["account_info"]["balance"])+"`` for username ``"+str(account_data["account_info"]["accname"])+"``"
        except MCAPI.APIException as exc:
            if exc.message == "CERR_AUTH_FAIL_ACCTOK":
                request.respond_cmd_temp(cleandoc("""
                    :stop_sign: Mattermost account seems to not be bound to any drink-terminal account. :(
                    Use ``/drink-bind-account <drink-terminal-username> <drink-terminal-password>`` to bind this Mattermost account to your drink-terminal account.
                    """))
                return
            raise exc


        try:
            cmd = data["text"] = data["text"].strip()
            if data["text"] == "" or data["text"].lower() == "help":
                msg += "\nUse ``/drink [count]<shortcut>`` and one of the following shortcuts to pay for ``$count * $shortcut``.\n\n|shortcut|price|Description|\n|---|---|---|"

                for s in account_data["shortcuts"]:
                    if int(s["vislevel"]) >= 2:
                        msg += "\n|"+s["short"]+"|"+s["amount"]+"|"+s["description"]+"|"
                request.respond_cmd_temp(msg)
                return

            count = None
            shortcut = None

            mat = re.match(r"(\d*)\s*(\w+)", cmd)
            if mat is None:
                request.respond_cmd_temp(msg+"\n:stop_sign: Invalid input: Nothing useful matched.")
                return

            (count, sc) = mat.groups()

            if count == "":
                count = 1

            count = int(count)
            if count < 1:
                request.respond_cmd_temp(msg+"\n:stop_sign: Invalid input: count < 1")
                return

            for s in account_data["shortcuts"]:
                if s["short"] == sc:
                    shortcut = s
                    break

            if shortcut is None:
                request.respond_cmd_temp(msg+"\n:stop_sign: Invalid input: no such shortcut :(\nUse ``/drink`` without any parameters for a list of shortcuts.")
                return
            else:
                handle.do_transaction(shortcut["target"], str(int(shortcut["amount"])*count), shortcut["reason"])
                account_data = handle.get_account_info(True)

                # Infcoin-IPC
                self.bot.modules[self.TEAM_ID]["inf-coin"].award_infcoins(data["user_id"], 100, "drink-use, ts="+str(datetime.datetime.now().replace(microsecond=0).isoformat()))

                self.bot.debug_chan("``/drink success: @"+data["user_name"]+' --'+str(int(shortcut["amount"])*count)+'--> '+str(shortcut["target"])+'``')
                request.respond_cmd_temp("## :white_check_mark: Success! :)\n:arrow_right:Available credits:``"+str(account_data["account_info"]["balance"])+"``"+
                    "\n:white_check_mark: Sucessfully paid **``"+str(int(shortcut["amount"])*count)+"``** TO **``"+str(shortcut["target"])+"``** FOR **``"+str(shortcut["reason"])+"``** :beers:"
                    )

        except MCAPI.APIException as exc:
            if exc.message == "CERR_AUTH_FAIL_ACCTOK":
                msg += "\n:stop_sign: Mattermost account seems to not be bound to any drink-terminal account. :("

            elif exc.message == "CERR_FAILED_TO_SEND":
                msg += "\n:stop_sign: Failed to send drink-credits. Balance exceeded? Sending too much? :(\nTried to send **``"+str(int(shortcut["amount"])*count)+"``** TO **``"+str(shortcut["target"])+"``** FOR **``"+str(shortcut["reason"])+"``**"

            elif exc.message == "CERR_AUTH_FAIL_INVALID_token_secret":
                msg += "\n:stop_sign: Mattermost failed to secure the payments subsystem. This is usually a transient error and you can retry immediately. :("


            request.respond_cmd_err(msg)
