<?php

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

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

class RadioInput extends SelectableDataInputFieldTag {
	const TAG = 'radio-input';
	const DEFAULT_TEMPLATE = 'radioInput';
	const CHECKED_ATTRIBUTE = 'data-checked';
	const TITLE_ATTRIBUTE = self::ATTRIBUTE_PREFIX . 'title';
	const OPTION_VALUE = self::ATTRIBUTE_PREFIX . 'option-value';
	const OPTION_NAME = self::ATTRIBUTE_PREFIX . 'option-name';

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

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

		$title = $this->attributes[self::TITLE_ATTRIBUTE] ?? $this->attributes[self::FIELD_SET_VALUE_ATTRIBUTE] ?? '';

		$parser->setData('title', $title);
		$parser->setData('option-value', $this->attributes[self::OPTION_VALUE] ?? null);
		$parser->setData('option-name', $this->attributes[self::OPTION_NAME] ?? null);

		$value = $this->attributes[self::OPTION_VALUE];
		$postValue = $this->getCurrentFieldValue() ?? $this->attributes[self::FIELD_SET_VALUE_ATTRIBUTE] ?? null;
		if (is_array($postValue) && in_array($value, $postValue)) $postValue = $value;
		if (
			(key_exists(self::CHECKED_ATTRIBUTE, $this->attributes) &&
			 ($postValue === null || $this->attributes[self::CHECKED_ATTRIBUTE] !== 'soft')) ||
			($postValue == $value)
		){
			$parser->setData('checked', 'checked' );
		}

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

	public static function getTagHtml(string $fieldName, string $value, string $title, string $innerHtml, bool $checked = false):string {
		return '<pad-' . self::TAG . ' ' .
		       self::FIELD_NAME_ATTRIBUTE . '="' . htmlspecialchars($fieldName) . '" ' .
		       self::TITLE_ATTRIBUTE . '="' . htmlspecialchars($title) . '" ' .
		       ($checked ? self::CHECKED_ATTRIBUTE : '') . ' ' .
		       self::OPTION_VALUE . '="' . htmlspecialchars($value) . '" >' .
		       $innerHtml .
		       '</pad-' . self::TAG . '>'
			;
	}
}