<?php

namespace Planaday\Utility\DataGrouping\IdHandling;

use ArrayAccess;
use Exception;
use Planaday\Utility\DataGrouping\UUIDGenerator;
use Planaday\Utility\Debug\Log\Logging;

class IdManager implements ArrayAccess {
	use Logging;
	public function __construct(protected UUIDGenerator $uuidGenerator) {}

	/** @var string[] */
	protected array $ids = [];

	protected function generateId(): string {
		try {
			return $this->uuidGenerator->generateUUIDv4();
		} catch ( Exception ) {
			return uniqid();
		}
	}

	public function offsetExists( mixed $offset ): bool {
		return true;
	}

	public function offsetGet( mixed $offset ): string {
		if ( !isset( $this->ids[ $offset ] ) ) {
			$this->ids[ $offset ] = $this->generateId();
		}

		return $this->ids[ $offset ];
	}

	public function offsetSet( mixed $offset, mixed $value ): void {
		$this->logWarning('IdManager does not support setting ids');
	}

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

	public function reset(): void {
		$this->ids = [];
	}
}