<?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 RadioButtonFormElement extends AbstractFormElement {
    public array $itemKeys = array();
    public array $itemValues = 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 and $this->itemValues
     *
     * @return void
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    private function setKeysAndValues(): void {
        HelperFormElement::getKeyValueListFromSqlEnumSpec($this->attributes, $this->itemKeys, $this->itemValues);
    }

    /**
     * @return void
     */
    private function setDefaults(): void {
        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 (isset($this->attributes[F_FE_DATA_MATCH_ERROR])) $this->htmlAttributes[F_FE_DATA_MATCH_ERROR] = $this->attributes[F_FE_DATA_MATCH_ERROR];
        if (isset($this->attributes[F_FE_DATA_ERROR])) $this->htmlAttributes[F_FE_DATA_ERROR] = $this->attributes[F_FE_DATA_ERROR];
        if (isset($this->attributes[FE_AUTOFOCUS])) $this->htmlAttributes[FE_AUTOFOCUS] = $this->attributes[FE_AUTOFOCUS];

        $this->htmlAttributes[FE_TYPE] = $this->attributes[FE_TYPE];
        if ($this->attributes[FE_DYNAMIC_UPDATE] === 'yes') $this->htmlAttributes[FE_DATA_LOAD] = 'data-load';
        $this->htmlAttributes[FE_INPUT_AUTOCOMPLETE] = 'off';
    }
}