<?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 UpdateTask
{
    public $writer = TaskWriter::class;
    public $finder = TaskFinder::class;
    // public $eventBus = EventBus::class;

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

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

        $m = $this->finder->get($taskId);
        if (!$m) {
            return $ret->addError('__Invalid task.__');
        }

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

        if ($title === $m->getTitle()) {
            $title = null;
        }
        if ($spots === $m->getSpots()) {
            $spots = null;
        }

        if ((null !== $title) or (null !== $spots)) {
            $this->writer->update($taskId, $title, $spots);
        }

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

        return $ret;
    }
}
