<?php

namespace Planaday\Html\NodeTags\Utility;

use DateTime;
use DateTimeInterface;
use DOMElement;
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\DateAndTimeUtility;
use Planaday\Utility\DependencyInjection\Attributes\Transient;

#[Transient]
class Date implements Tag {
	use TagCore;

	public function __construct(
		protected DateAndTimeUtility $dateUtility
	) {}

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

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

		$time = $this->attributes["time"] ?? null;
		$format = $this->attributes["format"] ?? null;
		$fallback = $this->attributes["fallback"] ?? null;

		if (is_int($time)) $time = new DateTime( "@$time");

		if (!$time instanceof DateTime) {
			$textNode = $outputFragment->ownerDocument->createTextNode( $fallback );
			$outputFragment->prepend( $textNode );
			return $outputFragment;
		}

		if ( is_string( $format ) ) {
			$outputText = $time->format($format);
		} else {
			$outputText = $this->dateUtility->getReadableDate( $time );
		}

		/** @var DOMElement&ParserNode $timeNode */
		$timeNode = $outputFragment->ownerDocument->createElement("time");
		$timeNode->appendChild( $outputFragment->ownerDocument->createTextNode( $outputText ) );
		$timeNode->setAttribute("datetime", $time->format(DateTimeInterface::ATOM));

		$outputFragment->prepend( $timeNode );

		return $outputFragment;
	}

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