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

from inspect import cleandoc


# pylint: disable=wrong-import-position
from AbstractCommand import AbstractCommand
from AbstractPublicWS import AbstractPublicWS
class CommandCurriculaSave(AbstractCommand,AbstractPublicWS):
    TRIGGER = "curricula-save"
    CONFIG = {"display_name": "somebot-command", "auto_complete": True,
              "auto_complete_hint": "",
             }
    USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = "Generate save-code for curricula.fsinf.at."


    def on_POST(self, request, data):
        att = [{
            "text": "Delete this post.",
            "color": "#ff0000",
            "actions": [{
                "name": ":wastebasket: Delete this post and all associated data. :wastebasket:",
                "integration": {"url": self.URL+"/interactive", "context": {"action": "delete_self"}}
                }]
            }]

        chan = self.bot.api.create_dm_channel_with(data['user_id'])
        post = self.bot.api.create_post(chan['id'], "### Generating curricula.fsinf.at storage ...", {"attachments":att, "context":{"curricula_fsinf":{}}})

        post["message"] = cleandoc("""
            ## ** https://curricula.fsinf.at storage**
            Please copy the following code into the https://curricula.fsinf.at storage section.
            ```
            """+post["id"]+"""
            ```
            There are **``"""+str(len(str(post["props"]["context"]["curricula_fsinf"])))+""" bytes``** of additional data stored in this message.
            """)
        post["props"].update(dict({"attachments":att}))
        self.bot.api.update_post(post["id"], message=post["message"], is_pinned=post["is_pinned"], has_reactions=None, props=post["props"])
        request.respond(200, {})


    def on_POST_interactive(self, request, data):
        if data["context"]["action"] == "delete_self":
            self.bot.api.delete_post(data["post_id"])


    def on_public_GET(self, request, data):
        splitpath = request.path.strip("/").split("/")

        if len(splitpath) != 2:
            request.respond_public(400, {"error":"no code given"})
            return

        post = self.bot.api.get_post(splitpath[1], exc=False)
        if "props" in post and "context" in post["props"] and "curricula_fsinf" in post["props"]["context"]:
            self.bot.api.create_post(post['channel_id'], "``AUTODELETE-WEEK`` Somebody just accessed this storage.\nIf this was not you consider creating a new storage post, migrate data and then delete this storage post, also consider contacting @someone.", root_id=post["id"])
            request.respond_public(200, post["props"]["context"]["curricula_fsinf"])
            return

        request.respond_public(400, {"error":"invalid code given"})


    def on_public_POST(self, request, data):
        splitpath = request.path.strip("/").split("/")

        if len(splitpath) != 2:
            request.respond_public(400, {"error":"no code given"})
            return

        post = self.bot.api.get_post(splitpath[1], exc=False)
        if "props" in post and "context" in post["props"] and "curricula_fsinf" in post["props"]["context"] and self.bot.api._my_user_id == post["user_id"]:
            if post["props"]["context"]["curricula_fsinf"] == data:
                request.respond_public(200, {"status":"unchanged"})
                return

            post["props"]["context"]["curricula_fsinf"] = data
            post["message"] = cleandoc("""
                ## ** https://curricula.fsinf.at storage**
                Please copy the following code into the https://curricula.fsinf.at storage section.
                ```
                """+post["id"]+"""
                ```
                There are **``"""+str(len(str(post["props"]["context"]["curricula_fsinf"])))+""" bytes``** of additional data stored in this message.
                """)
            att = [{
                "text": "Delete this post.",
                "color": "#ff0000",
                "actions": [{
                    "name": ":wastebasket: Delete this post and all associated data. :wastebasket:",
                    "integration": {"url": self.bot.modules[list(self.bot.modules.keys())[0]][self.TRIGGER].URL+"/interactive", "context": {"action": "delete_self"}}
                    }]
                }]

            post["props"].update(dict({"attachments":att}))
            saved_post = self.bot.api.update_post(post["id"], message=post["message"], is_pinned=post["is_pinned"], has_reactions=None, props=post["props"], exc=False)

            if "status_code" in saved_post and saved_post["status_code"] == 400 and saved_post['id'] == 'api.post.update_post.permissions_time_limit.app_error':
                request.respond_public(500, {"status":"post too old to update. TODO: write new post?"})
                return

            request.respond_public(200, {"status":"stored"})
            return

        request.respond_public(400, {"error":"invalid code given/something failed"})

