<?php

namespace Planaday\Html\NodeTags;

use DOMElement;
use Planaday\Html\Nodes\NodeData;
use Planaday\Html\Nodes\ParserNode;
use Planaday\Utility\Debug\Log\Logging;

trait TagCore {
	use Logging;

	protected DOMElement&ParserNode $originalNode;
	protected NodeData $nodeData;

	/** @var array<string, mixed> */
	protected array $config = [];
	protected ?string $tagTitle = null;

	/** @var array<string, mixed> */
	protected array $attributes = [];

	public function setOriginalNode( DOMElement&ParserNode $node ): void {
		$this->originalNode = $node;
	}

	public function setAttribute( string $key, mixed $value ): void {
		$this->attributes[$key] = $value;
	}

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

	/**
	 * @return array<string, mixed>
	 */
	public function getConfig(): array {
		return $this->config;
	}

	public function getTagTitle(): ?string {
		return $this->tagTitle;
	}

	protected function getTemplate(string $templateType = '', ?string $templateNameOverride = null, ?string $dirOverride = null):string {
		$selectedTemplateName = $templateNameOverride ??
		                        $this->attributes[TagCoreConstants::TEMPLATE_ATTRIBUTE] ??
		                        TagCoreConstants::DEFAULT_TEMPLATE;

		$pathWithoutDir =
			('/' . $templateType . "Templates/") .
			$selectedTemplateName .
			'.html';

		$path =  ($dirOverride ?? $this->getTagDir()) . $pathWithoutDir;

		if (file_exists($path)) $fileContents = file_get_contents( $path );

		if (!isset($fileContents) || $fileContents === false){
			$fileContents = '<!-- could not load template ' . htmlspecialchars($pathWithoutDir) . ' -->';
			$this->logError('Failed to load template ' . $pathWithoutDir, ['path' => $path]);
		}
		return $fileContents;
	}

	public function getCurrentTemplateName(): string {
		return $this->attributes[TagCoreConstants::TEMPLATE_ATTRIBUTE] ?? TagCoreConstants::DEFAULT_TEMPLATE;
	}

	public abstract function getTagDir(): string;

	public function destroy(): void {
		if(isset($this->originalNode)) $this->originalNode->destroyPhpReferences();
		unset($this->originalNode);
	}

	public function __destruct() {
		$this->destroy();
	}
}