import time

from controllers.base import Controller
from resources import types
from controllers.todos import Todos
from controllers.marks import action


class Works(Controller):
    resource = types.Work

    @action
    def active(self):
        return next((w for w in self.rows.standing() if not w.parked and w.data.get("agent", "") == self.agent), None)

    def _sectioned(self, r) -> None:
        r.logged = time.time()

    def _for_todo(self, n: int) -> list:
        return [w for w in self.rows.standing() if int(w.todo) == int(n)]

    def _unparked(self) -> list:
        return [w for w in self.rows.standing() if not w.parked]

    @action
    def create(self, title: str, abstract: str = "", brief: str = "", **data):
        self._gate(int(self._given(data).todo))
        return super().create(title, abstract, brief, **data)

    def _gate(self, todo: int = 0) -> None:
        busy = self.active()
        if busy and busy.todo:
            self._refuse(f'todo {busy.todo} is in hand as work {busy.n}: park it with journal work park "<why>", '
                          f'or finish it with journal todo done {busy.todo} --how "<how>", before starting another')
        if busy:
            self._refuse(f'work {busy.n} is open: end it with journal work end --how "<what landed>", '
                          f'or set it aside with journal work park "<why>", before starting another')
        if todo:
            row = Todos(self.record, actor=self.actor).load(todo)
            if row.completed:
                self._refuse(f"todo {row.n} is already done")
            held = row.assigned or ""
            if held and held != self.agent:
                self._refuse(f"todo {row.n} is assigned to {held}; nobody else may take it")
        self._handled("open", todo=todo)
