<?php

namespace Planaday\Html\NodeTags\Utility;

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

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

		$outputFragment = $this->originalNode->getUsableDocumentFragment();

		$selectedStyle = $this->attributes["selected-style"] ?? null;
		if ( $selectedStyle != null ) {
			return $outputFragment->getNodeFromTemplate("<pad-utility-style href='../Styles/$selectedStyle.css'/>");
		}

		$href = $this->attributes["href"] ?? null;
		if ( $href == null ) {
			throw new TagNotFullyInitializedException("The href attribute is not set");
		}

		return $outputFragment->getNodeFromTemplate("<script class='pad-script'>PadUtil.ensureStylesheetOnce('$href')</script>");
	}

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