<?php

namespace Planaday\Html\Parsers\NodeParsers;

use DOMAttr;
use DOMElement;
use DOMNode;
use Planaday\Html\Nodes\NodeData;
use Planaday\Html\Nodes\ParserNode;
use Planaday\Html\Parsers\DynamicDataParsers\DynamicDataParser;
use Planaday\Html\Parsers\StringInterpolationParser;
use Planaday\Utility\Debug\Log\Logging;
use Planaday\Utility\DependencyInjection\Attributes\Scoped;

#[Scoped]
class NodeAttributeParser implements NodeParser {
	use Logging;

	protected NodeData $nodeData;

	public function __construct(protected DynamicDataParser $dataParser, protected StringInterpolationParser $preParser) {
		$this->nodeData = new NodeData();
	}

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

	public function modifyNode( DOMNode&ParserNode $node ): void {
		if ( !$node instanceof DomElement ) {
			return;
		}

		/** @var DomElement&ParserNode $node */

		$customTag = $node->getAssociatedTag();

		$this->preParser->setNodeData( $this->nodeData );

		for ( $i = count($node->attributes) - 1; $i >= 0; $i-- ) {
			/** @var DOMAttr $attribute */
			$attribute = $node->attributes->item($i);
			$this->logDebug( "Parsing attribute: " . $attribute->name );
			if (str_starts_with($attribute->name, '_:') && str_ends_with($attribute->name, ':_')) {
				$cleanName = substr($attribute->name, 2, -2);

				if ($customTag !== null){
					$customTag->setAttribute(
						$cleanName,
						$this->dataParser->parseRaw($attribute->value, $this->nodeData->data)
					);
				} else {
					$node->setAttribute(
						$cleanName,
						$this->dataParser->parseForString($attribute->value, $this->nodeData->data)
					);
				}

				$node->removeAttribute($attribute->name);
				continue;
			}

			$updatedValue = $this->preParser->parse($attribute->value);
			$node->setAttribute($attribute->name, $updatedValue);
			$customTag?->setAttribute( $attribute->name, $updatedValue );
		}
	}
}