# ruff: noqa: F821

class Module:
    config = {"step": {
        "type": "integer",
        "label": {"ru": "Шаг", "en": "Step"},
        "min": 1,
        "max": 100,
        "default": 1,
    }}
    pages = [{
        "id": "main",
        "title": {"ru": "Счётчик", "en": "Counter"},
        "elements": [
              {"id": "count", "type": "metric", "label": {"ru": "Значение", "en": "Value"}},

              {

                  "id": "reset",

                  "type": "form",

                  "action": "reset",

                  "label": {

                  "ru": "Задать значение",



                  "en": "Set value",



              },

              }],
    }]

    async def init(self): await self.publish()

    async def publish(self):
        count = await app.db.get("count", default=0)
        await app.ui.set("main", {"count": count})
        return count

    @loader.command("counter", source="both")
    async def counter(self, ctx):
        count = await self.publish()
        step = await app.config.get("step", 1)
        try:
            await app.inline.form(ctx.chat_id, str(count), [[{
                "text": "+",
                "callback": "increment",
                "values": {"amount": step},
            }]])
        except RuntimeError: await ctx.reply(str(count))

    @loader.callback(fields={"amount": {"type": "integer", "min": 1, "max": 100, "default": 1}})
    async def increment(self, ctx):
        count = await app.db.get("count", default=0)
        await app.db.set("count", count + ctx.values["amount"])
        count = await self.publish()
        await ctx.edit(str(count))
        await ctx.answer()

    @loader.action(fields={"value": {"type": "integer", "min": 0, "max": 1000, "default": 0}}, confirm=True)
    async def reset(self, ctx):
        await app.db.set("count", ctx.values["value"])
        return {"count": await self.publish()}

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