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

import datetime
import threading
from inspect import cleandoc

import logging
logger = logging.getLogger(__name__)

# pylint: disable=wrong-import-position
from AbstractCommand import AbstractCommand
class CommandJoinAll(AbstractCommand):
    TRIGGER = "join-all"
    CONFIG = {"display_name": "somebot-command", "auto_complete": True,
              "auto_complete_hint": "[<weeks; default=3>]"
             }
    USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = AbstractCommand.ICON_PRIVATE+"Join active public channels. considers channels with 7 posts+ in the last x weeks. default 3 weeks. There is no undo."


    def __init__(self, team_id, skip_chann_ids):
        super().__init__(team_id)

        self.skip_chann_ids = skip_chann_ids
        self.channel_index = None
        self.channel_index_th = None


    def on_register(self):
        self._create_slash_command()
        self.channel_index_th = threading.Timer(10.0, self._index_channels)
        self.channel_index_th.setName("CommandJoinActive::_index_channels()")
        self.channel_index_th.setDaemon(True)
        self.channel_index_th.start()


    def _index_channels(self):
        if self.channel_index_th != threading.current_thread():
            logger.warning("_index_channels(): thread mismatch")
            return

        logger.info("_index_channels(): started")
        new_dict = {}
        for chan in self.bot.api.get_team_channels(self.TEAM_ID):
            if chan["id"] in self.skip_chann_ids:
                continue

            posts = []
            for post in self.bot.api.get_posts_for_channel(chan["id"]):
                if not post["type"].startswith("system_"):
                    posts.append(post)

                if len(posts) == 7:
                    break

            if len(posts) > 0:
                new_dict[chan["id"]] = min([x["create_at"] for x in posts])

        self.channel_index = new_dict
        self.channel_index_th = threading.Timer(3600.0, self._index_channels)
        self.channel_index_th.setName("CommandJoinActive::_index_channels()")
        self.channel_index_th.setDaemon(True)
        self.channel_index_th.start()
        logger.info("_index_channels(): done")


    def on_POST(self, request, data):
        if self.channel_index is None:
            request.respond_cmd_err("``/"+self.TRIGGER+"`` The channel indexer didnt finish yet. try again in a few minutes")
            return

        try:
            td = datetime.timedelta(weeks=int(data["text"].strip()))
        except:
            td = datetime.timedelta(weeks=3)

        timestamp = int((datetime.datetime.now()-td).timestamp())*1000

        msg = ""
        for chan in self.bot.api.get_team_channels(self.TEAM_ID):
            #check against ban list and get the last 7 posts, if all of them are newer than min_timestamp: join
            if chan["id"] in self.channel_index and chan["id"] not in self.skip_chann_ids and self.channel_index[chan["id"]] > timestamp:
                self.bot.api.add_user_to_channel(chan["id"], data["user_id"])
                msg += "\n + ~"+chan["name"]

        request.respond_cmd_temp(cleandoc("""
            ## :white_check_mark: Success! :)
            By default it wont join you into channels that had less than 5 messages posted within the last 2 weeks.
            If you want to be joined into less active channels give the command an integer number of weeks to to consider.
            /join-active 8 will join you into channels that had less than 5 messages posted within the last 2 months.
            Anyway: joined the following active public channels in the team (A reload might be needed to display the updated list of channels):
            {}
            """).format(msg))
