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

import datetime
import os
import re
from inspect import cleandoc


# pylint: disable=wrong-import-position
from AbstractCommand import AbstractCommand
class CommandFreeDrink(AbstractCommand):
    TRIGGER = "free-drink"
    CONFIG = {"display_name": "somebot-command", "auto_complete": True,
              "auto_complete_hint": "",
             }
    USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = AbstractCommand.ICON_PRIVATE+"used to log our free drink for the onboarding event."


    def __init__(self, team_id, datadir, email_rex_str):
        super().__init__(team_id)
        self.datadir = datadir
        self.email_rex = re.compile(email_rex_str)


    def on_POST(self, request, data):
        user = self.bot.api.get_user(data["user_id"])

        if self.email_rex.match(user["email"]):
            filename = self.datadir + data["user_id"]
            if not os.path.isfile(filename):
                with open(filename, "w") as file:
                    file.write(data["user_id"]+" -- "+data["user_name"]+" -- "+datetime.datetime.now().isoformat()+"\n")
                    request.respond_cmd_temp(cleandoc("""
                        ## :white_check_mark: Success! :)
                        #### Enjoy your drink!
                        """))
                    #self.bot.api.add_user_to_channel("m5sik9jwmib6mfpnpcmsib1h7w", data["user_id"])
                    self.bot.debug_chan(":white_check_mark: ``/free-drink`` logged: ``"+data["user_name"]+"``")

            else:
                request.respond_cmd_err("It seems you already logged your free drink before.")
                self.bot.debug_chan(":x: ``/free-drink`` already logged for: ``"+data["user_name"]+"``")
        else:
            request.respond_cmd_err("You are not eligible for a free drink. If you think this was a mistake, contact @someone")
            self.bot.debug_chan(":x: ``/free-drink`` not eligible: ``"+data["user_name"]+"``")
