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



from AbstractCommand import *
class CommandSpoilerAdv(AbstractCommand):
    TRIGGER = "spoiler-adv"
    CONFIG = {"display_name": "somebot-command", "auto_complete": True,
              "auto_complete_hint": "<post permalink> <spoiler-text>",
             }
    USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = "Attach/replace spoiler-text on any of your messages. (--remove to remove) Must be able to edit said message."


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

        if len(msg_text[1]) > 7000:
            request.cmd_respond_text_temp("``/spoiler-adv`` failed: Spoiler-text must be smaller than 7000 characters :(\nYour text is: "+str(len(msg_text[1]))+" characters long.")
            return

        try:
            splitpath = msg_text[0].strip().strip("/").split("/")
            if splitpath[4] == "pl":
                pl_post_id = splitpath[5]
        except:
            request.cmd_respond_text_temp("``/spoiler-adv`` failed: The first parameter is not a valid post permalink. :(")
            return

        if len(msg_text) == 1:
            request.cmd_respond_text_temp("``/spoiler-adv`` failed: It seems like you did not supply any spoiler-text. (use --remove to remove a spoiler text) :(")
            return

        post = self.bot.api.get_post(pl_post_id)
        if post['user_id'] != data['user_id']:
            request.cmd_respond_text_temp("``/spoiler-adv`` failed: Is the permalinked post yours? :(")
            return

        att = [{
            "text": "This post contains spoilers.",
            "actions": [{
                "name": ":ghost: show me the spoilers :ghost:",
                "integration": {"url": self.URL+"/interactive", "context": {"action": "show_spoiler", "spoiler":msg_text[1]}}
                }]
            }]

        post["props"].update(dict({"attachments":att}))

        if msg_text[1] == "--remove":
            del post["props"]["attachments"]

        self.bot.api.patch_post(splitpath[5], post["message"], post["props"])
        request.cmd_respond_text_temp("### ``Done.`` :)")


    def on_POST_interactive(self, request, data):
        if data["context"]["action"] == "show_spoiler":
            request.respond(200, {"skip_slack_parsing":True, "ephemeral_text": data["context"]["spoiler"]})
