<?php

namespace App\Collection;

use App\Entity\Task;
use App\Enum\TaskStatus;

/**
 * @implements \IteratorAggregate<int, Task>
 */
final class TaskCollection implements \IteratorAggregate
{
    /** @var list<Task> */
    private array $tasks = [];

    /**
     * @param list<Task> $tasks
     */
    public function __construct(array $tasks = [])
    {
        foreach ($tasks as $task) {
            $this->add($task);
        }
    }

    private function add(Task $task): void
    {
        $this->tasks[] = $task;
    }

    public function getIterator(): \Iterator
    {
        return new \ArrayIterator($this->tasks);
    }

    public function filterInactive(): self
    {
        $this->tasks = [...array_filter(
            $this->tasks,
            fn (Task $t) => $t->getStatus() !== TaskStatus::Inactive
        )];

        return $this;
    }

    public function sortByDueDate(): self
    {
        usort($this->tasks, fn (Task $a, Task $b) => $a->getDate() <=> $b->getDate());

        return $this;
    }

    public function sortByDueDateDesc(): self
    {
        usort($this->tasks, fn (Task $a, Task $b) =>
            $a->getDate() === null || $b->getDate() === null
                ? $a->getDate() <=> $b->getDate()
                : $b->getDate() <=> $a->getDate()
        );

        return $this;
    }
}
