<?php

namespace Planaday\Html\Tags\Form\CourseSearch\LabelSelect;

use ArrayAccess;
use Countable;
use Planaday\Entities\Course\CourseController;
use Planaday\Entities\Course\PostRequest\CourseSearchFieldEnum;
use Planaday\Html\Tags\Form\GenericInput\CheckboxInput\CheckboxInput;
use Planaday\Html\Tags\Form\SelectableDataInputFieldTag;
use Planaday\Html\Tags\Tag;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;
use Traversable;

class LabelSelect extends Tag {
	const TAG = 'label-select';
	const DEFAULT_TEMPLATE = 'labelSelect';

	protected CourseController $courseController;

	/**
	 * @param Container $registry
	 *
	 * @throws InjectionImpossibleException
	 */
	public function __construct(Container $registry) {
		$this->courseController = $registry->getInstance(CourseController::class);
		parent::__construct(__DIR__, self::DEFAULT_TEMPLATE, $registry);
	}

	public function buildTag(): string {
		$parser = $this->getNewParser();

		$labels = $this->courseController->getUniqueLabelsCourse();

		$parser->setUnsafeData('labelSelections', $this->buildInputFieldHtml($labels));
		$parser->injectAttribute(
			$this->getRecursiveVersionOfAttribute(SelectableDataInputFieldTag::FIELD_CLASS_ATTRIBUTE),
			CourseSearchFieldEnum::class
		);

		return $parser->parse($this->getTemplate());
	}

	/**
	 * @param ArrayAccess<int|string, string>&Traversable<int|string, string>&Countable $labels
	 *
	 * @return string
	 */
	private function buildInputFieldHtml(ArrayAccess&Traversable&Countable $labels):string {
		$inputFieldHtml = '';
		$postField = CourseSearchFieldEnum::LABELS;

		foreach ($labels as $label){
			$inputFieldHtml .= CheckboxInput::getTagHtml($postField, $label, $label, $label);
			$inputFieldHtml .= CheckboxInput::getClosingTagHtml();
		}

		return $inputFieldHtml;
	}
}