# 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 random
import re
import threading
from inspect import cleandoc

from webdav3.client import Client


# pylint: disable=wrong-import-position
from AbstractCommand import AbstractCommand
class CommandCoronaPresenceLogger(AbstractCommand):
    TRIGGER = "cpl"
    CONFIG = {"display_name": "somebot-command", "auto_complete": False}
    CONFIG["description"] = AbstractCommand.ICON_PRIVATE+"Corona-presence-logging"
    USEINFO = cleandoc("""
        ``/cpl`` is our approach to corona related presence logging at fsinf.
        Use ``/cpl --yes`` to get your presence at fsinf today logged.
        Consider using this command if you stay longer than a few seconds at fsinf (grabbing a Drink for an exam).

        This information is retained for about a month.

        If we get informed of somebody testing positive for COVID-19, we shall inform anyone who was at fsinf on the same days.
        If you shall test positive for COVID-19, please inform us, so we can inform anyone who was at fsinf on the same days as you.
        """)


    def __init__(self, team_id, datadir, dav_options=None):
        super().__init__(team_id)
        self.datadir = datadir
        self.dav_options = dav_options


    def on_POST(self, request, data):
        data['text'] = data['text'].strip()

        if re.match(r"^(-|—|–)+meme$", data["text"]) and self.dav_options:
            self.channel_index_th = threading.Timer(1.0, self._upload_meme, [request, data])
            self.channel_index_th.setName("CommandCoronaPresenceLogger::upload_meme()")
            self.channel_index_th.setDaemon(True)
            self.channel_index_th.start()

            request.respond_cmd_chan("``AUTODELETE-DAY`` **``CPL, OIDA!``**", props={"cpl-meme-upload-todo":"todo"})

        elif re.match(r"^(-|—|–)+", data['text']):
            filename = self.datadir + datetime.date.today().isoformat()+"__"+data["user_id"]
            with open(filename, "a") as file:
                file.write(data["user_id"]+" -- "+data["user_name"]+" -- "+datetime.datetime.now().isoformat()+"\n")
                request.respond_cmd_temp(cleandoc("""
                    ## :white_check_mark: Success! :)
                    #### ``Your presence at FSINF today has been logged.``
                    This information is retained for about a month.

                    #### :point_right: If you turn out to be COVID-positive please inform @someone to issue a warning to other possibly exposed people. :point_left:
                    """))
                self.bot.api.add_user_to_channel("m5sik9jwmib6mfpnpcmsib1h7w", data["user_id"])
                self.bot.debug_chan("``/cpl`` presence logged: ``"+data["user_name"]+"``")

        else:
            request.respond_cmd_err("Please use ``/cpl --yes`` to confirm your presence at fsinf. \n\n"+self.USEINFO)


    # racecondition if called in the same channel too fast. nonissue?
    def _upload_meme(self, request, data):
        post_cnt = 0
        for post in self.bot.api.get_posts_for_channel(data["channel_id"]):
            post_cnt += 1
            if post_cnt > 20:
                break

            if "cpl-meme-upload-todo" in post["props"] and post["props"]["cpl-meme-upload-todo"] == "todo":
                client = Client(self.dav_options)
                file_list = client.list()
                del file_list[0]
                client.download_file(random.choice(file_list), '/tmp/cpl-meme.png')

                self.bot.api.create_post(post["channel_id"], '``AUTODELETE-DAY`` **``CPL, OIDA!``**', props={"from_webhook":"true"}, filepaths=['/tmp/cpl-meme.png'], root_id=post["root_id"])
                self.bot.api.delete_post(post["id"])
