# Mattermost Bot module.
#  Copyright (c) 2016-2022 by Someone <someone@somenet.org> (aka. Jan Vales <jan@jvales.net>)
#  published under MIT-License
#
# This command relies on the priviledged DB-Cleaner maint script.


from inspect import cleandoc

import logging
logger = logging.getLogger(__name__)


# pylint: disable=wrong-import-position
from AbstractCommand import AbstractCommand
class CommandCourseIsMeh(AbstractCommand):
    TRIGGER = "course-is-meh"
    CONFIG = {"display_name": "somebot-command", "auto_complete": True,
              "auto_complete_hint": "[<reason>]",
             }
    CONFIG["auto_complete_desc"] = CONFIG["description"] = AbstractCommand.ICON_DM+"Use in a course channel. Increments the 'course is meh atm' counter. The optional reason is sent to fsinf to look into."


    def __init__(self, team_id, datadir):
        super().__init__(team_id)
        self.datadir = datadir
        self.course_stats = {}


    def on_POST(self, request, data):
        msg_text = data['text'].strip()
        chan = self.bot.api.get_channel(data["channel_id"])
        import pprint
        pprint.pprint(chan)

        if chan["name"] in ["town-square", "off-topic"] or chan["display_name"][0] == "=" or chan["type"] != "O":
            request.respond_cmd_err("``/"+self.TRIGGER+"`` must be used in a course channel.")
            return

        if len(msg_text) > 5000:
            request.respond_cmd_err("``/"+self.TRIGGER+"`` failed: reason-text must be smaller than 5000 characters :(\nYour text is: "+str(len(msg_text[1]))+" characters long.")
            return

        # do actual action
        self.meh_courses_inc(data["channel_name"])
        if len(msg_text) > 0:
            self.bot.api.create_post("cmr1s9d6678e7y94iw3jgwte3c", "``AUTODELETE-DAY`` ``/"+self.TRIGGER+"`` used by ``@"+data["user_name"]+"`` in ``"+data["team_domain"]+"::"+data["channel_name"]+"``\n```\n"+data["text"].strip()+"\n```")

        request.respond_cmd_temp("## :white_check_mark: Success! :)")


    def on_shutdown(self):
        self.meh_courses_dumpstats()

    def on_SIGUSR1(self, sigusr1_cnt):
        self.meh_courses_dumpstats()


    def meh_courses_inc(self, course, amount=1):
        if course in self.course_stats:
            self.course_stats[course] += amount
        else:
            self.course_stats[course] = amount


    def meh_courses_dumpstats(self):
        stats = self.course_stats.copy()
        self.course_stats = {}
        self.bot.dump_stats_json(stats, self.datadir+"course_stats-"+self.TEAM_ID+".json", cleandoc("""
            This week's ``/course-is-meh`` -stats #mmstats.
            Use this command in a course channel to increment the counter if the course is currently suboptimal for you. This command produces no output in that channel.
            It doesnt really matter if its because you forgot your laptop-charger or the course just changed its modalities and you turned negative without any way to become positive again.
            If you supply a reason it will be forwarded to fsinf to take a look at. (We want to know when you forgot your laptop chargers! XD )

            |course|meh-ness|
            |---|---:|
        """))
