from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING: from router import Event

class Module:
    config = app.config.fields().add("step", app.config.field("integer").label({"ru": "Шаг", "en": "Step"}).bounds(1, 100).default(1))
    pages = [app.ui.define("main", {"ru": "Счётчик", "en": "Counter"})
             .add(app.ui.element("count", "metric", {"ru": "Значение", "en": "Value"}))
             .add(app.ui.element("history", "table", {"ru": "История", "en": "History"}, columns=["value"]))]

    @loader.command("record", source="telegram", access="owner")
    async def record(self, ctx: Event) -> None:
        snapshot = await app.config.snapshot().load()
        record = await app.db.record("counter", {"count": 0}).load()
        record.increment("count", snapshot.get("step"))
        await record.save()
        count = record.get("count")
        async with app.ui.page("main") as page:
            page.metric("count", count)
            history = page.table("history")
            if len(history.rows()) >= 100: history.remove(0)
            history.row(value=count)
        file = await app.files.store("count.txt", str(count).encode(), ttl=3600)
        task = await app.tasks(self.saved, values={"count": count}).after(60).create()
        await app.logs.bind(command="record").info("Counter saved", count=count, task=task.id)
        await ctx.reply(f"Count: {count}. File: {file.id}")

    @loader.task(fields={"count": {"type": "integer", "required": True}})
    async def saved(self, ctx: Event) -> None:
        await app.logs.info("Scheduled counter", count=ctx.values["count"])
