# 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 TACommandWipeChannel(AbstractCommand):
    TRIGGER = "ta-wipe-channel"
    CONFIG = {"display_name": "somebot-command", "auto_complete": True,
              "auto_complete_hint": "'--really-all'|<username>",
             }
    CONFIG["auto_complete_desc"] = CONFIG["description"] = AbstractCommand.ICON_PRIVATE+"Delete all not-pinned posts in channel (optionally: only by <username>). There is no undo. [TEAM_ADMIN]"


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

        user = self.bot.api.get_user_by_username(data["text"].strip(), exc=False)
        if data["text"].strip() in ["--really-all", "--system"] and not user:
            request.respond_cmd_err("``/"+self.TRIGGER+"`` parameter must be '--really-all', '--system' or a valid username.")
            return

        # needs indirection. see iterators.
        posts = list(self.bot.api.get_posts_for_channel(data['channel_id']))
        for post in posts:
            if post["is_pinned"]:
                continue

            if (data["text"].strip() == "--really-all") or (data["text"].strip() == "--system" and post["type"].startswith("system_")) or (data["text"].strip() != "" and user["id"] == post["user_id"]) or (data["text"].strip() == ""):
                self.bot.api.delete_post(post["id"])

        self.bot.debug_chan("``/ta-wipe-channel "+data["text"].strip()+"`` used by ``@"+data["user_name"]+"`` in ``"+data["team_domain"]+"::"+data["channel_name"]+"``")
        request.respond_cmd_temp("## :white_check_mark: Success! :)")
