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

import pprint
import re

from inspect import cleandoc


# pylint: disable=wrong-import-position
from AbstractPublicWS import AbstractPublicWS
from AbstractWSHandler import AbstractWSHandler
class WSGuestControl(AbstractWSHandler, AbstractPublicWS):
    TRIGGER=NAME = "guestcontrol"


    def __init__(self, email_rex_str, guest_teams_and_channels, primary_teamid):
        super().__init__()

        self.email_rex = re.compile(email_rex_str)
        self.guest_teams_and_channels = guest_teams_and_channels
        self.primary_teamid = primary_teamid


    def on_WS_EVENT(self, data):
        user =  self.bot.api.get_user(data["data"]["user"]["id"])

        # promote guest with correct email
        if self.email_rex.match(user["email"]) and "system_guest" in user["roles"]:
            print("WSGuestControl: Promoting guest.")
            self.bot.api.promote_a_guest(user["id"])

            chan = self.bot.api.create_dm_channel_with(user["id"])
            self.bot.api.create_post(chan["id"], cleandoc("""
                ### ``Your account has been converted to a FULL-USER account!``
                You are now able to use all the features mattermost and this instance has to offer!
                # :thumbsup:
                """))

            return True

        # demote user with incorrect email (email no longer changable to invalid - delete this?)
        elif not self.email_rex.match(user["email"]) and not "system_guest" in user["roles"]:
            print("WSGuestControl: Demoting user.")
            pprint.pprint(user)
            self.bot.command_stats_inc("WSGuestControl: demote user -- should not happen?")
            self.bot.api.demote_a_user(user["id"])

            for team_id, chan_ids in self.guest_teams_and_channels.items():
                for chan_id in chan_ids:
                    self.bot.api.add_user_to_team(team_id, user["id"], exc=False)
                    self.bot.api.add_user_to_channel(chan_id, user["id"], exc=False)

            chan = self.bot.api.create_dm_channel_with(user["id"])
            self.bot.api.create_post(chan["id"], cleandoc("""
                ## ``Confirm your student email to get full access to Mattermost``
                Your account is currently a [guest account](https://docs.mattermost.com/deployment/guest-accounts.html), which means your user expirience is limited due to privacy, copyright and licencing reasons and you are restricted to these channels:
                * Beratung (Consultation)
                * Guest-Talk

                Guest accounts are deleted after 30 days of inactivity.

                To gain full access to all channels and features you need to go to your Account Settings and change your email to ``eXXXXXXXX@student.tuwien.ac.at`` and then click on the link in the confirmation email. You will then get full access within an hour.
                """))

        else:
            print("WSGuestControl: Profile change we dont care about.")


    def on_public_POST(self, request, data):
        import pprint
        pprint.pprint(data)

        # todo: test if email seems valid.

        channels = [ch_id for tid,ch_id_set in self.guest_teams_and_channels.items() for ch_id in ch_id_set]
        message = "Welcome to FSInf-Mattermost. Guest accounts are very limited due to privacy, copyright and licencing reasons and are deleted after 30 das of inactivity. Set your student's eMail address (eXXXXXXXX@student.tuwien.ac.at) as soon as possible."
        request.respond_public(200, self.bot.api.invite_guests_to_team_by_email(self.primary_teamid, data["email"], channels, message))
