<?php

namespace Signteer\Web\Admin\Page\Sheet;

use Plainwork\Http\Request;
use Plainwork\Http\Redirect;
use Plainwork\Ui\Html;
use Signteer\Core\Action\Task\CreateTask;
use Signteer\Core\Finder\SheetFinder;

final class CreateTaskPage
{
    public $action = CreateTask::class;
    public $sheetFinder = SheetFinder::class;

    public function __invoke(Request $request)
    {
        $sheetId = $request->getQueryParam('sheet');
        if (!$sheetId) {
            return new Redirect('../../..');
        }

        $sheet = $this->sheetFinder->get($sheetId);
        if (!$sheet) {
            return new Redirect('../../..');
        }

        $html = new Html();

        $form = $html->form();
        $form->add($html->textInput('title')->setRequired());
        $form->add($html->numberInput('spots')->setRequired()->setMin(1));

        $values = $form->grab($request);
        if ($values) {
            if ($form->isValid()) {
                $res = ($this->action)($sheetId, $values['title'], $values['spots']);
                if ($res->isOk()) {
                    $taskId = $res->getReturn();

                    $ret = '__Task created__';
                    $ret = $html->main($ret);
                    $ret->title = $html->el('h1', '__Action result__');
                    $ret->afterContentMenu->add($html->link('admin/sheet/' . $sheetId, [], '__View sheet__'));
                    $ret->afterContentMenu->add($html->link('admin/sheet', [], '__View all sheets__'));
                    $ret->afterContentMenu->add($html->link('admin/sheet/' . $sheetId . '/task', [], '__Manage sheet\'s tasks__'));
                    $ret->afterContentMenu->add($html->link('admin/sheet/' . $sheetId . '/task/create', [], '__Add new task__'));

                    return $ret;
                }

                $form->addErrors($res->getErrors());
            }
        }

        $ret = $html->blockList()
            ->add($html->dl('__What to do__', $form->input('title')))
            ->add($html->dl('__Number of spots__', $form->input('spots')))
            ;
        if ($form->getErrors()) {
            $ret->add($html->dl('__Error__', $html->formErrors($form->getErrors())));
        }
        $ret->add($html->dl(null, $html->button('__Create task__')));
        $ret = $form->setContent($ret);

        $ret = $html->main($ret);
        $ret->title = $html->el('h1', '__New task__');

        return $ret;
    }
}
