<?php

namespace Planaday\Utility\DependencyInjection;

use Exception;
use Planaday\Utility\DataGrouping\UUIDGenerator;
use Planaday\Utility\Debug\Log\Logging;
use Planaday\Utility\DependencyInjection\Attributes\Scoped;

#[Scoped]
class Scope {
	use Logging;

	protected ComponentRegister $scopeRegister;
	public string $scopeId;

	public function __construct() {
		try{
			$this->scopeId = UUIDGenerator::generateUUIDv4Static();
		} catch ( Exception) {
			$this->scopeId = uniqid("", true);
		}
		$this->scopeRegister = new ComponentRegister();
		$this->scopeRegister->set(Scope::class, $this);
		$this->loggingScopeId = $this->scopeId;
		$this->logInfo($this->scopeId . ' scope created');
	}

	public function __destruct() {
		$this->logInfo($this->loggingScopeId . ' scope destroyed');
	}

	/**
	 * @template C
	 * @param class-string<C> $class
	 *
	 * @return C|null
	 */
	public function get(string $class){
		$instance = $this->scopeRegister->get($class);
		if ($instance) $this->logDebug($this->loggingScopeId . ' got ' . $class);
		return $instance;
	}

	/**
	 * @template C
	 * @template I of C
	 * @param class-string<C> $class
	 * @param I|null $object
	 *
	 * @return void
	 */
	public function set(string $class, $object): void{
		$this->logInfo($this->loggingScopeId . ' set ' . $class);
		$this->scopeRegister->set($class, $object);
	}

	public function destroy(): void{
		unset($this->scopeRegister);
	}
}