<?php

namespace Planaday\Html\NodeTags\Course\DetailLink;

use DOMNode;
use Planaday\Entities\Course\CourseUtility;
use Planaday\Entities\Course\DTO\Course;
use Planaday\Html\Nodes\NodeData;
use Planaday\Html\Nodes\ParserNode;
use Planaday\Html\NodeTags\Course\ListItem\CourseListItemSettings;
use Planaday\Html\NodeTags\InnerContentControl;
use Planaday\Html\NodeTags\Tag;
use Planaday\Html\NodeTags\TagCore;
use Planaday\Html\NodeTags\TagNotFullyInitializedException;
use Planaday\Html\Parsers\NodeParsers\TagMarkers\TestDataTag;
use Planaday\Utility\DependencyInjection\Attributes\Transient;

#[Transient]
class DetailLink implements Tag, TestDataTag {
	use InnerContentControl;
	use TagCore;

	public function __construct(
		protected CourseUtility $courseUtility,
		protected CourseListItemSettings $listItemSettings,
	) {
		$this->config = [
			"courseButtonText" => $this->listItemSettings->getCourseButtonText(...),
		];
	}

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

		$nodeData = clone ($this->nodeData ?? new NodeData());
		$course = $this->attributes["course"] ?? $this->nodeData->data["course"] ?? null;

		if ( ! ( $course instanceof Course ) ) {
			throw new TagNotFullyInitializedException( "The course is not set" );
		}

		$nodeData->data["detailLink"] = $this->courseUtility->getDetailLink( $course );

		$node = $this->originalNode->getNodeFromTemplate($this->getTemplate());
		$node->setExtendedNodeData( $nodeData );

		$innerContent = $this->getInnerContentFragment($this->originalNode);
		$innerContent->setExtendedNodeData( $this->originalNode->getExtendedNodeData() );
		$this->replaceContentTagWithinFragment("pad-content", $innerContent, $node);

		return $node;
	}

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

	public function injectTestData(): void {
		$this->nodeData->data['course'] ??= new Course( 1 );
	}
}