<?php

namespace IMATHUZH\Qfq\Core\Form\FormElement;

use IMATHUZH\Qfq\Core\Form\Form;
use IMATHUZH\Qfq\Core\Helper\HelperFormElement;
use IMATHUZH\Qfq\Core\Helper\Support;

class SelectFormElement extends AbstractFormElement {
    public array $itemKeys = array();
    public array $itemValues = array();
    public array $classValue = array();

    // selectBS
    public array $itemGroupKeys = array();
    public array $itemGroupValues = array();

    // Optional counts for filter display
    public array $itemCounts = array();

    /**
     * @param $attributes
     * @param Form|null $form
     * @throws \CodeException
     * @throws \DbException
     * @throws \DownloadException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     * @throws \UserFormException
     * @throws \UserReportException
     */
    public function __construct($attributes, ?Form $form = null) {
        parent::__construct($attributes, $form);

        $this->setKeysAndValues();
        $this->setDefaults();
    }

    /**
     * Fills $this->itemKeys, $this->itemValues and $this->classValue
     *
     * @return void
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    private function setKeysAndValues(): void {
        HelperFormElement::getKeyValueListFromSqlEnumSpec($this->attributes, $this->itemKeys, $this->itemValues, $this->itemGroupKeys, $this->itemGroupValues, $this->classValue, $this->itemCounts);
    }

    /**
     * @return void
     */
    private function setDefaults(): void {
        $this->htmlAttributes['title'] = $this->attributes[FE_TOOLTIP];
        if (isset($this->attributes[FE_AUTOFOCUS])) $this->htmlAttributes[FE_AUTOFOCUS] = $this->attributes[FE_AUTOFOCUS];
        if (isset($this->attributes[F_FE_DATA_PATTERN_ERROR])) $this->htmlAttributes[F_FE_DATA_PATTERN_ERROR] = $this->attributes[F_FE_DATA_PATTERN_ERROR];
        if (isset($this->attributes[F_FE_DATA_REQUIRED_ERROR])) $this->htmlAttributes[F_FE_DATA_REQUIRED_ERROR] = $this->attributes[F_FE_DATA_REQUIRED_ERROR];

        if ($this->attributes[FE_DYNAMIC_UPDATE] === 'yes') $this->htmlAttributes[FE_DATA_LOAD] = 'data-load';
        $this->htmlAttributes[ATTRIBUTE_DATA_REFERENCE] = $this->attributes[FE_DATA_REFERENCE];

        // Multi Select
        if (isset($this->attributes[FE_SIZE]) && $this->attributes[FE_SIZE] > 1) {
            $this->htmlAttributes[FE_SIZE] = $this->attributes[FE_SIZE];
            $this->htmlAttributes[HTML_ATTR_TYPE] = HTML_ATTR_TYPE_CHECKBOX;
        }
    }

}