<?php

namespace PublishPress\FuturePro\Modules\Notifications\Collections;

use PublishPress\FuturePro\Modules\Notifications\Interfaces\NotificationModelInterface;
use PublishPress\FuturePro\Modules\Notifications\Models\NotificationModel;

class NotificationCollection implements \Iterator, \Countable
{
    /**
     * @var array
     */
    private $rawData = [];

    /**
     * @var NotificationModelInterface[]
     */
    private $loadedModels = [];

    /**
     * @var int
     */
    private $position = 0;

    public function __construct(array $notifications)
    {
        $this->rawData = $notifications;
    }

    public function current(): NotificationModelInterface
    {
        if (!isset($this->loadedModels[$this->position])) {
            // Lazy load: only create model when needed
            $notification = $this->rawData[$this->position];
            $model = new NotificationModel();
            $model->loadFromRow($notification);

            $this->loadedModels[$this->position] = $model;
        }

        return $this->loadedModels[$this->position];
    }

    public function key(): int
    {
        return $this->position;
    }

    public function next(): void
    {
        $this->position++;
    }

    public function rewind(): void
    {
        $this->position = 0;
    }

    public function valid(): bool
    {
        return isset($this->rawData[$this->position]);
    }

    public function count(): int
    {
        return count($this->rawData);
    }
}
