<?php

namespace Planaday\Html\Tags\Form\GenericInput\MappedIntRadio;

use Planaday\Html\Tags\Form\GenericInput\RadioInput\RadioInput;
use Planaday\Html\Tags\Form\SelectableDataInputFieldTag;
use Planaday\Html\Tags\Tag;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;

class MappedIntRadio extends SelectableDataInputFieldTag {
	const TAG = 'mapped-int-radio';
	const DEFAULT_TEMPLATE = 'mappedIntRadio';

	const MAP_CONTEXT_INDEX = 'int->option mapping';

	/**
	 * @param Container $registry
	 *
	 * @throws InjectionImpossibleException
	 */
	public function __construct(Container $registry ) {
		parent::__construct(__DIR__, self::DEFAULT_TEMPLATE, $registry);
	}

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

		$attributes = [
			self::FIELD_SET_VALUE_ATTRIBUTE => $this->attributes[self::FIELD_SET_VALUE_ATTRIBUTE] ?? null,
		];

		$map = $this->context[self::MAP_CONTEXT_INDEX] ?? null;
		if (!is_array($map)) {
			$this->logError('No mapping provided for mapped int radio');
			return '';
		}

		$html = '';
		foreach ($map as $int => $value){
			$attributes[RadioInput::OPTION_VALUE] = $int;
			$attributes[RadioInput::OPTION_NAME] = $value;
			$attributes[RadioInput::TITLE_ATTRIBUTE ] = $value;

			$html .= Tag::getParsableTag(RadioInput::TAG, $attributes) . "<br>";
		}

		return $parser->parse($html);
	}
}