<?php

namespace Planaday\Html\NodeTags\Utility;

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 UserTextTemplate implements Tag {
	use TagCore;

	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);
		$outputFragment = $this->originalNode->getUsableDocumentFragment();
		$text = $node->textContent;
		$outputFragment->setExtendedNodeData((new NodeData())->setData($data));
		$textNode = $outputFragment->ownerDocument->createTextNode($text);
		$outputFragment->prepend($textNode);

		return $outputFragment;
	}

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