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



# pylint: disable=wrong-import-position
from AbstractCommand import AbstractCommand
class CACommandModDelPostText(AbstractCommand):
    TRIGGER = "mod-del-post-text"
    CONFIG = {"display_name": "somebot-command", "auto_complete": True,
              "auto_complete_hint": "<permalink> <reason>",
             }
    CONFIG["auto_complete_desc"] = CONFIG["description"] = AbstractCommand.ICON_PUBLIC+"Remove post-text, but dont delete post. Run in same channel. Cannot be undone! [CHANNEL_ADMIN]"


    def on_POST(self, request, data):
        self._require_channel_admin(data) # will throw an exception if not. (Dont try-except: Its handled up the stack.)

        msg_text = data['text'].strip().split(" ", 1)

        if len(msg_text) == 1:
            request.respond_cmd_err("``/"+self.TRIGGER+"`` It seems like you did not supply any reason-text.")
            return

        if len(msg_text[1]) > 15000:
            request.respond_cmd_err("``/"+self.TRIGGER+"`` reason-text must be smaller than 15000 characters :(\nYour text is: "+str(len(msg_text[1]))+" characters long.")
            return

        try:
            splitpath = msg_text[0].strip().strip("/").split("/")
            if splitpath[4] == "pl":
                post = self.bot.api.get_post(splitpath[5])
        except:
            request.respond_cmd_err("``/"+self.TRIGGER+"`` The first parameter is not a valid post-permalink or the permalinked post has been deleted.")
            return

        if post["channel_id"] != data["channel_id"]:
            request.respond_cmd_err("``/"+self.TRIGGER+"`` Must be executed in the same channel as the permalinked post.")
            return

        if "cmd" in post["props"] and post["props"]["cmd"] != self.TRIGGER:
            request.respond_cmd_err("``/"+self.TRIGGER+"`` The command **``/"+post["props"]["cmd"]+"``** already affects this post. Undo said command before applying this one.")
            return

        if post["message"].strip() == "":
            request.respond_cmd_err("``/"+self.TRIGGER+"`` doesnt work on empty messages and cant be undone.\nIf you are an admin_a you can use ``/mod-get-post-text`` to view the original text. :(")
            return

        # do actual action
        att = [{"color":"#f35912", "text": "**Post-text removed. Reason:**\n"+msg_text[1]}]
        post["props"].update(dict({"attachments":att, "somebot_removed_post_text":post["message"], "cmd":self.TRIGGER}))

        self.bot.api.update_post(splitpath[5], message=None, is_pinned=post["is_pinned"], has_reactions=post["has_reactions"], props=post["props"])
        self.bot.debug_chan("``/"+self.TRIGGER+" "+data["text"].strip()+"`` used by ``@"+data["user_name"]+"`` in ``"+data["team_domain"]+"::"+data["channel_name"]+"``")
        request.respond_cmd_temp("## :white_check_mark: Success! :)")
