<?php

namespace Signteer\Web\Front\Page\Sheet;

use Plainwork\Http\Request;
use Plainwork\Http\Redirect;
use Plainwork\Ui\Html;
use Signteer\Core\Criteria\SignupCriteria;
use Signteer\Core\Criteria\TaskCriteria;
use Signteer\Core\Finder\SheetFinder;
use Signteer\Core\Finder\SignupFinder;
use Signteer\Core\Finder\TaskFinder;

final class ViewSheetPage
{
    public $finder = SheetFinder::class;
    public $taskFinder = TaskFinder::class;
    public $signupFinder = SignupFinder::class;

    public function __invoke(Request $request)
    {
        $id = $request->getQueryParam('sheet');
        $m = $this->finder->get($id);
        if (!$m) {
            return (new Redirect('..'));
        }

        $c = (new TaskCriteria())->whereSheetId('=', $id);
        $tasks = $this->taskFinder->find($c);

        $c = (new SignupCriteria())->whereSheetId('=', $id);
        $signups = $this->signupFinder->findWithVolunteer($c);

        $html = new Html();

        $ret = $html->blockList()->setSpacing(3);
        foreach ($tasks as $task) {
            $signups_ = array_filter($signups, fn($e) => ($e->getTaskId() === $task->getId()));

            $signupLink = $html->link('./signup/create', ['task' => $task->getId()], '__Sign up__');
            $signupLinkShown = false;

            $ret_ = $html->el('ol');
            for ($i = 1; $i <= $task->getSpots(); $i++) {
                $signup_ = ($signups_) ? array_shift($signups_) : null;
                if ($signup_) {
                    $volunteer_ = $signup_->getVolunteer();
                    $v = $volunteer_->getTitle();
                    $ret_->append($html->el('li', $v));
                } else {
                    if (!$signupLinkShown) {
                        $ret_->append($html->el('li', $signupLink));
                        $signupLinkShown = true;
                    } else {
                        $v = '__(Empty)__';
                        $v = $html->el('strong', $v);
                        $ret_->append($html->el('li', $v));
                    }
                }
            }

            $head_ = $html->el('h3', $task->getTitle());
            $ret_ = $html->blockList($head_, $ret_);

            $ret->add($ret_);
        }

        $ret = $html->main($ret);

        return $ret;
    }
}
