<?php

namespace Planaday\Html\Parsers\NodeParsers;

use DOMNode;
use Planaday\Html\Nodes\NodeData;
use Planaday\Html\Nodes\ParserNode;
use Planaday\Html\Parsers\NodeParsers\TagMarkers\RefreshSpecificIds;
use Planaday\Html\Parsers\NodeParsers\TagMarkers\RefreshUniqueId;
use Planaday\Utility\DataGrouping\IdHandling\IdManager;
use Planaday\Utility\Debug\Log\Logging;
use Planaday\Utility\DependencyInjection\Attributes\Scoped;

#[Scoped]
class ParserGeneratedId implements NodeParser {
	use Logging;
	protected NodeData $nodeData;

	public function __construct(protected IdManager $idManager ) {}

	public function setNodeData( NodeData $nodeData ): void {
		$this->nodeData = $nodeData;
	}

	public function modifyNode( DOMNode&ParserNode $node ): void {
		$tag = $node->getAssociatedTag();

		if ( ! isset( $this->nodeData )  ) {
			return;
		}

		$this->nodeData->data['autoGenerated'] ??= [];
		$this->nodeData->data['autoGenerated']['id'] ??= $this->getResetManager();

		if ( $tag === null ) {
			return;
		}

		if ( $tag instanceof RefreshUniqueId){
			$this->nodeData->data['autoGenerated']['id'] = $this->getResetManager();
		}

		if ( $tag instanceof RefreshSpecificIds){
			$manager = clone $this->nodeData->data['autoGenerated']['id'];
			foreach ($tag->getIdsToRefresh() as $id) {
				unset($manager[$id]);
			}
			$this->nodeData->data['autoGenerated']['id'] = $manager;
		}
	}

	public function getResetManager(): IdManager {
		$manager = clone $this->idManager;
		$manager->reset();
		return $manager;
	}
}