<?php

namespace Planaday\Html\NodeTags\DayPart\Details\Location;

use Planaday\Api\ApiException\InvalidResponseException;
use Planaday\Entities\DayPart\DTO\DayPart;
use Planaday\Entities\Location\Exception\LocationNotFoundException;
use Planaday\Entities\Location\LocationController;
use Planaday\Html\Nodes\NodeData;
use Planaday\Html\NodeTags\Tag;
use Planaday\Html\NodeTags\TemplateOnlyTag;
use Planaday\Utility\DependencyInjection\Attributes\Transient;

#[Transient]
class Location implements Tag {
	use TemplateOnlyTag;

	public function __construct(
		protected LocationController $locationController,
	) {}

	protected function prepareData( NodeData $nodeData ): void {
		$daypart = $this->attributes["daypart"] ?? $this->nodeData->data["daypart"] ?? null;

		if (!$daypart instanceof DayPart){
			return;
		}

		$nodeData->data["location"] = function () use ($daypart) {
			$locationId = $daypart->getLocationIds()[0] ?? null;
			if ( $locationId == null || $locationId == '' || $locationId == 0 ) {return null;}
			try {
				return $this->locationController->getLocation($locationId);
			} catch (LocationNotFoundException|InvalidResponseException $e) {
				$this->logWarning( "Location not found: " . $e->getMessage() );
				return null;
			}
		};
	}

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