<?php

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

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

class CheckboxInput extends SelectableDataInputFieldTag {
	const TAG = 'check-box';
	const DEFAULT_TEMPLATE = 'checkbox';
	const TITLE_ATTRIBUTE = 'data-title';
	const DISABLED_ATTRIBUTE = 'data-disabled';
	const CHECKED_ATTRIBUTE = 'data-checked';
	const FALSE_VALUE_ATTRIBUTE = self::ATTRIBUTE_PREFIX . 'false-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->addScript( $this->getScriptPath("checkboxNesting"));
		$parser->addStylesheet( $this->getStylePath("checkboxNesting"));
		$parser->addStylesheet( $this->getStylePath());

		$value = $this->attributes[self::FIELD_SET_VALUE_ATTRIBUTE] ?? null;
		$title = $this->attributes[self::TITLE_ATTRIBUTE] ?? null;
		$postValue = $this->getCurrentFieldValue();
		if (is_array($postValue) && in_array($value, $postValue)) $postValue = $value;

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

		$parser->setData('disabled', key_exists(self::DISABLED_ATTRIBUTE, $this->attributes) ? 'disabled' : '');
		if (key_exists(self::FALSE_VALUE_ATTRIBUTE, $this->attributes)){
			$parser->setData('false-value', $this->attributes[self::FALSE_VALUE_ATTRIBUTE]);
			$parser->setCondition('withFalseValue', true);
		}

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

	public static function getTagHtml(string $fieldName, string $label, string $title, string $value, bool $checked = false, bool $selfClosing = false, ?string $template = null):string {
		return '<pad-' . self::TAG . ' ' .
		       self::FIELD_TITLE_ATTRIBUTE . '="' . htmlspecialchars($label) . '" ' .
		       self::FIELD_NAME_ATTRIBUTE . '="' . htmlspecialchars($fieldName) . '" ' .
		       self::TITLE_ATTRIBUTE . '="' . htmlspecialchars($title) . '" ' .
		       self::FIELD_SET_VALUE_ATTRIBUTE . '="' . htmlspecialchars($value) . '" ' .
		       ($checked ? self::CHECKED_ATTRIBUTE : '') . ' ' .
		       ($template !== null ? self::TEMPLATE_ATTRIBUTE . '="' . htmlspecialchars($template) . '" ' : '') . ' ' .
		       ($selfClosing ? '/>' : '>')
		;
	}

	public static function getClosingTagHtml():string {
		return '</pad-' . self::TAG . '>';
	}
}