<?php

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

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

class AttributeSelect extends SelectableDataInputFieldTag {
	const TAG = 'attribute-select';
	const DEFAULT_TEMPLATE = 'attributeSelect';
	const NULL_TOGGLE_ATTRIBUTE = 'data-no-null';
	const TRUE_TITLE_ATTRIBUTE = 'data-true-title';
	const FALSE_TITLE_ATTRIBUTE = 'data-false-title';
	const UNSET_TITLE_ATTRIBUTE = 'data-unset-title';
	const DEFAULT_VALUE_ATTRIBUTE = 'data-default-value';

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

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

		$parser->injectAttribute(self::FIELD_CLASS_ATTRIBUTE, $this->attributes[self::FIELD_CLASS_ATTRIBUTE] ?? null);

		$parser->setData('true-title', $this->attributes[self::TRUE_TITLE_ATTRIBUTE] ?? 'Ja');
		$parser->setData('false-title', $this->attributes[self::FALSE_TITLE_ATTRIBUTE] ?? 'Nee');
		$parser->setData('unset-title', $this->attributes[self::UNSET_TITLE_ATTRIBUTE] ?? '-');

		$hasNullOption = !key_exists(self::NULL_TOGGLE_ATTRIBUTE, $this->attributes);
		$parser->setCondition('has-null', $hasNullOption);

		$currentFieldValue = $this->getCurrentFieldValue() ?? $this->attributes[self::DEFAULT_VALUE_ATTRIBUTE] ?? null;

		if ($currentFieldValue === '1' || $currentFieldValue === 'ja'){
			$parser->setData('checked-1', 'data-checked');
		} elseif ($currentFieldValue === '0' || $currentFieldValue === 'nee' || !$hasNullOption){
			$parser->setData('checked-0', 'data-checked');
		} else {
			$parser->setData('checked-null', 'data-checked');
		}

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