<?php

namespace App\Modules\Shared\Domain\Data;

use ArrayAccess;
use ArrayIterator;
use Countable;
use IteratorAggregate;
use TypeError;

class DataGroupCollection implements Countable, ArrayAccess, IteratorAggregate
{

    private array $data;

    public function __construct(DataGroup ...$data)
    {
        $this->data = $data;
    }

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

    public function data()
    {
        return $this->data;
    }

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

    public function offsetExists(mixed $offset): bool
    {
        return isset($this->data[$offset]);
    }

    public function offsetGet(mixed $offset): DataGroup
    {
        return $this->data[$offset];
    }

    public function offsetSet(mixed $offset, mixed $value): void
    {
        if ($value instanceof DataGroup) {
            $this->data[$offset] = $value;
        } else throw new TypeError("Invalid value type");
    }

    public function offsetUnset(mixed $offset): void
    {
        unset($this->data[$offset]);
    }
}
