# 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.


import logging
logger = logging.getLogger(__name__)


# pylint: disable=wrong-import-position
from AbstractCommand import AbstractCommand
class DialogManagedReport(AbstractCommand):
    TRIGGER = "report"
    CONFIG = {"display_name": "somebot-command", "auto_complete": True,
              "auto_complete_hint": "<permalink> [<reason>]",
             }
    CONFIG["auto_complete_desc"] = CONFIG["description"] = AbstractCommand.ICON_PRIVATE+"Report given post. Run in same channel. Opens dialog if no reason is given."


    def __init__(self, team_id, report_chan_id):
        super().__init__(team_id)
        self.report_chan_id = report_chan_id


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

        try:
            splitpath = msg_text[0].strip().strip("/").split("/")
            if splitpath[4] == "pl":
                post = self.bot.api.get_post(splitpath[5])
        except:
            request.respond_cmd_err("``/"+self.TRIGGER+"`` The first parameter is not a valid post-permalink or the permalinked post has been deleted.")
            return

        if post["channel_id"] != data["channel_id"]:
            request.respond_cmd_err("``/"+self.TRIGGER+"`` Must be executed in the same channel as the permalinked post.")
            return

        # do actual action
        if len(msg_text) == 2:
            self.bot.api.create_post(self.report_chan_id, "``AUTODELETE-MONTH`` ``/"+self.TRIGGER+"`` used by ``@"+data["user_name"]+"`` in ``"+data["team_domain"]+"::"+data["channel_name"]+"``\n#### Reported post: "+msg_text[0]+"\nReason:\n```\n"+msg_text[1].strip()+"\n```")
            request.respond_cmd_temp("## :white_check_mark: Success! :)")

        else:
            dialog = {
                "callback_id": post["id"]+"-"+data["user_id"],
                "title": "Report post",
                "submit_label":"Report",
                "state": post["id"],
                "elements":[{
                    "display_name": "What's going on?",
                    "name": "report_reason",
                    "type": "radio",
                    "options": [{
                            "text": "It's annoying or not interesting",
                            "value": "not_interesting"
                        },{
                            "text": "I'm in this post and I don't like it",
                            "value": "im_in_it_and_i_dont_like_it"
                        },{
                            "text": "I think it shouldn't be on Mattermost",
                            "value": "should_not_be_on_mm"
                        },{
                            "text": "It's spam",
                            "value": "spam"
                        },{
                            "text": "Other reason (Fill in below)",
                            "value": "other_reason"
                        }
                    ],
                    "optional": False,
                    "default": "other_reason"
                },{
                    "display_name": "Other reason or additional details",
                    "placeholder": "Write a custom reason or additional details here.",
                    "name": "report_other_reason",
                    "type": "textarea",
                    "help_text": "The report is submitted to channel and team admin_as.",
                    "optional": True,
                }]
            }

            self.bot.api.open_dialog(data["trigger_id"], self.URL+"/dialog", dialog)
            request.respond()



    def on_POST_dialog(self, request, data):
        user = self.bot.api.get_user(data["user_id"])
        team = self.bot.api.get_team(data["team_id"])
        chan = self.bot.api.get_channel(data["channel_id"])

        if "report_other_reason" in data["submission"] and data["submission"]["report_other_reason"]:
            report_other_reason = "\nAdditional details/other reason:\n```\n"+data["submission"]["report_other_reason"].strip()+"\n```"
        else:
            report_other_reason = ""
            if "report_reason" in data["submission"] and data["submission"]["report_reason"] == "other_reason":
                request.respond(200, {"errors": {"report_reason": "Please write some details below, if selecting 'other reason'"}})
                return

        self.bot.api.create_post(self.report_chan_id, "``AUTODELETE-MONTH`` ``/"+self.TRIGGER+"`` used by ``@"+user["username"]+"`` in ``"+team["name"]+"::"+chan["name"]+"``\n#### Reported post: https://mattermost.fsinf.at/"+team["name"]+"/pl/"+data["state"]+"\nReason selected: **``"+data["submission"]["report_reason"]+"``**"+report_other_reason)
