<?php

namespace Signteer\Core\Action\Task;

use Signteer\Core\Action\ActionResult;
use Signteer\Core\Criteria\TaskCriteria;
use Signteer\Core\Finder\TaskFinder;
use Signteer\Core\Writer\TaskWriter;

final class CreateTask
{
    public $writer = TaskWriter::class;
    public $finder = TaskFinder::class;
    // public $eventBus = EventBus::class;

    public function __invoke(int $sheetId, string $title, int $spots): ActionResult
    {
        $ret = new ActionResult();

        $title = trim($title);
        if (!strlen($title)) {
            return $ret->addError('__Task title is required.__');
        }

        $c = (new TaskCriteria())->whereTitle('=', $title)->whereSheetId('=', $sheetId);
        $already = $this->finder->exists($c);
        if ($already) {
            return $ret->addError('__This task title is already in use.__');
        }

        $id = $this->writer->create($sheetId, $title, $spots);
        $ret->setReturn($id);

        // $this->eventBus->emit(new LocationCreated($id, $title));

        return $ret;
    }
}
