<?php

namespace Planaday\Html\Tags\Form;

use Planaday\Html\HtmlParser;
use Planaday\Utility\DataGrouping\PostFieldEnum;

abstract class SelectableDataInputFieldTag extends DataInputFieldTag {
	const FIELD_NAME_ATTRIBUTE = 'data-field-name';
	const FIELD_TITLE_ATTRIBUTE = 'data-field-title';
	const REQUIRED_ATTRIBUTE = 'data-required';
	const FIELD_CLASS_ATTRIBUTE = 'data-field-class';
	const FIELD_SET_VALUE_ATTRIBUTE = self::ATTRIBUTE_PREFIX . 'value';
	const PLACEHOLDER_ATTRIBUTE = 'data-field-placeholder';
	const FIELD_ID_OVERWRITE_ATTRIBUTE = 'data-field-id';

	protected function getNewParser(): HtmlParser {
		$parser = parent::getNewParser();

		$parser->injectAttribute(
			$this->getRecursiveVersionOfAttribute(self::FIELD_NAME_ARRAY_NAME),
			$this->getFullFieldName()
		);
		$parser->injectAttribute(
			$this->getRecursiveVersionOfAttribute(self::FIELD_NAME_ARRAY_INDEX),
			null
		);

		$parser->setData('field-id-name', $this->attributes[self::FIELD_NAME_ATTRIBUTE] ?? null);
		$parser->setData('overwrittenId', $this->attributes[self::FIELD_ID_OVERWRITE_ATTRIBUTE] ?? "overwritten-id-" . $parser->getParserUniqueId());
		$parser->setData('value', $this->attributes[self::FIELD_SET_VALUE_ATTRIBUTE] ?? null);
		$parser->setData('required', $this->getRequiredString());
		$parser->setData('field-title', $this->getSelectedFieldTitle());
		$parser->setData('placeholder', $this->attributes[self::PLACEHOLDER_ATTRIBUTE] ?? null);

		$currentValue = $this->getCurrentFieldValue() ?? $this->attributes[self::FIELD_SET_VALUE_ATTRIBUTE] ?? null;
		if(is_float($currentValue) || is_string($currentValue) || is_int($currentValue) || is_null($currentValue) )
			$parser->setData('field-value', $currentValue);

		return $parser;
	}

	protected function getFullFieldName(): string{
		return $this->getNextFieldNameArray($this->getSelectedFieldName());
	}

	private function getSelectedFieldName():?string {
		if (!isset($this->attributes[self::FIELD_NAME_ATTRIBUTE])) return null;
		$fieldName = $this->attributes[self::FIELD_NAME_ATTRIBUTE];
		$constName = strtoupper($fieldName);
		$enumClass = $this->attributes[self::FIELD_CLASS_ATTRIBUTE] ?? null;

		if (is_a($enumClass, PostFieldEnum::class, true)){
			$postFieldName = $enumClass::get($constName);
		}

		return (!isset($postFieldName) || $postFieldName == null) ? $fieldName : $postFieldName;
	}

	protected function getSelectedFieldTitle(): string{
		return $this->attributes[self::FIELD_TITLE_ATTRIBUTE] ?? $this->getFullFieldName();
	}

	protected function getRequiredString():string {
		return (isset($this->attributes[self::REQUIRED_ATTRIBUTE]) ? 'required' : '');
	}

	protected function isCurrentValueSetValue():bool {
		return $this->getCurrentFieldValue() == ($this->attributes[self::FIELD_SET_VALUE_ATTRIBUTE] ?? null);
	}
}