<?php

namespace Planaday\Html\NodeTags\Core\IfTag;

use DOMNode;
use Planaday\Html\NodeTags\InnerContentControl;
use Planaday\Html\NodeTags\Tag;
use Planaday\Html\NodeTags\TagCore;
use Planaday\Html\NodeTags\TagNotFullyInitializedException;
use Planaday\Html\Nodes\ParserNode;

class IfTag implements Tag {
	use TagCore;
	use InnerContentControl;

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

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

		$if = $this->attributes["if"] ?? null;
		$equals = $this->attributes["equals"] ?? null;
		$show = $if == ($equals ?? true);
		$or = isset($this->attributes["or"]);

		foreach ($this->attributes as $key => $value) {
			$this->logDebug("Checking " . $key . ", with value: ", $value);

			if (str_starts_with($key, "if-")) {
				$result = $value == ($equals ?? true);
				$show = $show && $result || $or && $result || $show && $or;
			}

			if (str_starts_with($key, "not-if-")) {
				$result = $value != ($equals ?? true);
				$show = $show && $result || $or && $result || $show && $or;
			}
		}

		$not = isset($this->attributes["not"]);
		$show = $show && !$not || !$show && $not;

		$this->logDebug("If tag is " . ($show ? "showing" : "hiding"));

		$innerContent = $this->getInnerContentFragment($this->originalNode);

		if ( $show ) {
			return $innerContent;
		} else {
			return $outputFragment;
		}
	}

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