import time

from core.chat_blob import ChatBlob
from core.command_param_types import Any, Int, Const, Options
from core.decorators import instance, command


@instance()
class NotesController:
    def inject(self, registry):
        self.db = registry.get_instance("db")
        self.text = registry.get_instance("text")
        self.account_service = registry.get_instance("account_service")

    def start(self):
        self.db.exec("CREATE TABLE IF NOT EXISTS notes ("
                     "id INT PRIMARY KEY AUTO_INCREMENT, "
                     "char_id INT NOT NULL, "
                     "note TEXT NOT NULL,"
                     "created_at INT NOT NULL,"
                     "INDEX char_id(char_id) USING BTREE)")

    @command(command="notes", params=[], access_level="member",
             description="Show your notes")
    def notes_list_cmd(self, request):
        alts = self.account_service.get_alts(request.sender.char_id)

        cnt = 0
        blob = ""
        for alt in alts:
            data = self.db.query("SELECT * FROM notes WHERE char_id = ? ORDER BY created_at DESC", [alt.char_id])
            alt_cnt = len(data)
            cnt += alt_cnt

            if alt_cnt:
                blob += f"\n<header2>{alt.name}</header2>\n"
                for row in data:
                    blob += f"» {row.note} {self.text.make_tellcmd('Remove', f'notes remove {row.id:d}')}\n"

        return ChatBlob(f"Notes for {alts[0].name} ({cnt:d})", blob)

    @command(command="notes", params=[Const("add"), Any("note")], access_level="member",
             description="Add a note")
    def notes_add_cmd(self, request, _, note):
        self.db.exec("INSERT INTO notes (char_id, note, created_at) VALUES (?, ?, ?)",
                     [request.sender.char_id, note, int(time.time())])

        return "Note added successfully."

    @command(command="notes", params=[Options(["rem", "remove"]), Int("note_id")], access_level="member",
             description="Remove a note")
    def notes_remove_cmd(self, request, _, note_id):
        note = self.db.query_single("SELECT n.*, p.name FROM notes n "
                                    "LEFT JOIN player p ON n.char_id = p.char_id "
                                    "WHERE n.id = ?",
                                    [note_id])

        if not note:
            return f"Could not find note with ID <highlight>{note_id}</highlight>."

        if self.account_service.get_main(request.sender.char_id).char_id \
                != self.account_service.get_main(note.char_id).char_id:
            return f"You must be a confirmed alt of <highlight>{note.name}</highlight> to remove this note."

        self.db.exec("DELETE FROM notes WHERE id = ?", [note_id])

        return f"Note with ID <highlight>{note_id}</highlight> deleted successfully."
