from nextpy_server.registry import action, defaults

_todos = [
    {"id": 1, "text": "Try the todo app", "done": False},
]
_next_id = 2

defaults(todos=_todos[:])


@action
def add_todo(text: str):
    global _next_id
    _todos.append({"id": _next_id, "text": text, "done": False})
    _next_id += 1
    return {"todos": _todos[:]}


@action
def toggle_todo(id: int):
    for t in _todos:
        if t["id"] == id:
            t["done"] = not t["done"]
    return {"todos": _todos[:]}


@action
def delete_todo(id: int):
    global _todos
    _todos = [t for t in _todos if t["id"] != id]
    return {"todos": _todos[:]}
