# ruff: noqa: F821

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from app import App
    from loader import loader
    from router import Event

    app: App

class Module:
    config = {"heading": {
        "type": "string",
        "label": {"ru": "Заголовок заметки", "en": "Note heading"},
        "default": "Note",
        "min": 1,
        "max": 40,
        "required": True,
    }}
    pages = [{
        "id": "main",
        "title": {"ru": "Заметка", "en": "Note"},
        "elements": [
            {"id": "heading", "type": "text"},
            {"id": "note", "type": "text", "label": {"ru": "Текст заметки", "en": "Note text"}},
            {"id": "save", "type": "form", "action": "save", "label": {"ru": "Сохранить заметку", "en": "Save note"}},
            {"id": "clear", "type": "button", "action": "clear", "label": {"ru": "Удалить заметку", "en": "Delete note"}},
        ],
    }]

    async def init(self) -> None: await self.publish()

    async def publish(self) -> str:
        note: str = await app.db.get("note", default="")
        heading: str = await app.config.get("heading", "Note")
        await app.ui.set("main", {"heading": heading, "note": note or "No note saved."})
        return note

    @loader.handler(event="config")
    async def changed(self, ctx: Event) -> None: await self.publish()

    @loader.action(access="owner", confirm=True)
    async def clear(self, ctx: Event) -> dict[str, str]:
        await app.db.set("note", "")
        return {"note": await self.publish()}

    @loader.command("note", access="owner", source="both")
    async def note(self, ctx: Event) -> None:
        value = ctx.args.strip()

        if len(value) > 800:
            await ctx.reply("The note must contain no more than 800 characters.")
            return
        if value: await app.db.set("note", value)

        note = await self.publish()
        heading: str = await app.config.get("heading", "Note")
        await ctx.reply(f"{heading}\n{note or 'No note saved.'}")

    @loader.action(fields={"text": {"type": "string", "label": {"ru": "Текст заметки", "en": "Note text"}, "min": 1, "max": 800, "required": True}}, access="owner")
    async def save(self, ctx: Event) -> dict[str, str]:
        await app.db.set("note", ctx.values["text"].strip())
        return {"note": await self.publish()}
