<?php

namespace Planaday\Utility\FormBuilder\InputFields;

use Planaday\Utility\FormBuilder\DataTypes\ArrayType;
use Planaday\Utility\FormBuilder\InputField;
use Planaday\Utility\FormBuilder\InvalidFormDataException;

/**
 * @template T
 * @implements InputField<T[]>
 */
class LayeredCheckboxesInput implements InputField {
	use BasicInputField{
		validate as traitValidate;
	}

	/**
	 * @param ArrayType<T> $type
	 */
	public function __construct(
		ArrayType $type
	) {
		$this->dataType = $type;
	}

	protected array $options = [];

	public function setOptions( array $options ): self {
		$this->options = [];

		foreach ( $options as $option ) {
			if ( is_array( $option ) ) {
				$this->options[] = $option;
				continue;
			}

			$this->options[] = [
				'value' => $option,
				'label' => $option
			];
		}

		return $this;
	}

	public function getOptions(): array {
		return $this->options;
	}

	public function validate(): bool|InvalidFormDataException {
		if (!$this->validateConditions()) return true;
		$basicValidate = $this->traitValidate();

		if ($this->value === null) return true;
		foreach ( $this->value as $val ) {
			$inArray = false;

			foreach ( $this->options as $option ) {
				if ( $option['value'] === $val ) {
					$inArray = true;
					break;
				}
			}

			if ( !$inArray ) {
				if ( $basicValidate === true ) {
					$basicValidate = new InvalidFormDataException();
				}

				$basicValidate->addError( 'LayeredCheckboxes', 'Input was not a valid option.' );
				return $basicValidate;
			}
		}

		return $basicValidate;
	}

	public function getImplJson(): array {
		return [
			"type"       => 'layeredCheckboxes',
			"options"     => $this->options
		];
	}
}