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

import re


REX_linesplit = re.compile(r"\xa0|\t|\s{4}")


from AbstractCommand import *
class CommandTissJoin(AbstractCommand):
    TRIGGER = "tissjoin"
    CONFIG = {"display_name": "somebot-command", "auto_complete": True,
        "auto_complete_hint": "<as-is-copy/paste of one TISS-LVA-Cockpit table>",
    }
    USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = "Parses input and tries to join every LVA-channel. There is no undo."


    def on_POST(self, request, data):
        result = ""
        lines = data["text"].splitlines()
        for line in lines:
            lva_line = REX_linesplit.split(line)
            if len(lva_line) < 2:
                continue

            lvaname = lva_line[1].strip().replace("&"," ").replace("-"," ").replace("|"," ").strip()
            if len(lvaname) < 5:
                continue

            if lvaname.startswith("Titel   Std") or lvaname.startswith("Summe   "):
                continue

            result += "\n+ ``"+lvaname+"``"

            # max 60 char length
            channel_results = self.bot.api.search_channel(self.TEAM_ID, lvaname[:60]) # max 60 char length

            if len(channel_results) == 0:
                result += "\n   + :stop_sign: could not find suitable channel"

            elif len(channel_results) == 1:
                channel = channel_results[0]
                result += "\n   + :white_check_mark: found channel: ~"+channel["name"]+"\n   + trying to join..."
                # no useful result
                self.bot.api.add_user_to_channel(channel["id"], data["user_id"])

            else:
                result += "\n   + :warning: multiple channels found. Join the correct channel(s) by clicking on their name. If they are not clickable, click on ``More...`` to download the full channel-list. Close the window once it opens."
                for channel in channel_results:
                    result += "\n     + ~"+channel["name"]+"\n"


        if result == "":
            request.cmd_respond_text_temp("### ``TISS-Join results``\nFailed to detect any courses. :(")

        request.cmd_respond_text_temp("### ``TISS-Join results``"+result)

