<?php

namespace Planaday\Html\NodeTags\Utility;

use DOMElement;
use DOMNode;
use Planaday\Html\Nodes\NodeData;
use Planaday\Html\Nodes\ParserNode;
use Planaday\Html\NodeTags\Tag;
use Planaday\Html\NodeTags\TagCore;
use Planaday\Html\NodeTags\TagNotFullyInitializedException;
use Planaday\Utility\DependencyInjection\Attributes\Transient;

#[Transient]
class UserHtml implements Tag {
	use TagCore;

	const AllowedTags = [
		'p',
		'i',
		'b',
		'strong',
		'div',
		'li',
		'ul',
		'ol',
		'root',
		'document-fragment'
	];

	public function getNewNode(): DOMNode&ParserNode {
		if ( !isset( $this->originalNode ) ){
			throw new TagNotFullyInitializedException("The OriginalNode is not set");
		}

		$template = $this->attributes["template"] ?? "";
		$data = $this->attributes["data"] ?? [];

		if ( !is_array($data) || !is_string($template) ) {
			throw new TagNotFullyInitializedException("input data is invalid");
		}

		$node = $this->originalNode->getNodeFromTemplate($template);
		$node = $this->sanitizeTags($node);

		$outputFragment = $this->originalNode->getUsableDocumentFragment();
		$outputFragment->setExtendedNodeData((new NodeData())->setData($data));
		$outputFragment->prepend($node);

		return $outputFragment;
	}

	public function getTagDir(): string {
		return __DIR__;
	}

	protected function sanitizeTags( DOMNode $node): string|DOMNode {
		if ($node instanceof DOMElement) {
			$tagName = $node->tagName;
			if (!in_array($tagName, self::AllowedTags)) {
				return $node->textContent;
			}
		}

		foreach ($node->childNodes as $childNode) {
			$result = $this->sanitizeTags($childNode);
			if ($result instanceof DOMNode) {
				continue;
			}

			$newNode = $node->ownerDocument->createTextNode($result);
			$node->replaceChild($newNode, $childNode);
		}

		return $node;
	}
}