<?php

namespace IMATHUZH\Qfq\Core\Form\FormElement;

use http\Encoding\Stream\Deflate;
use IMATHUZH\Qfq\Core\Form\FeFactory;
use IMATHUZH\Qfq\Core\Form\Form;
use IMATHUZH\Qfq\Core\Helper\Logger;
use IMATHUZH\Qfq\Core\Helper\Support;


class PillFormElement extends ContainerFormElement {
    public bool $isFirstPill = false;

    /**
     * @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
     * @var array $formElements Child Elements of this Container.
     *
     */
    public function __construct($attributes, ?Form $form = null) {
        parent::__construct($attributes, $form, false);
        $hrefName = $form == null ? 'noForm' : $form->specFinal[F_NAME];
        $this->htmlAttributes['href'] = '#' . $hrefName . '_' . $this->attributes[FE_ID]; //. '_' . $this->form->recordId;
        $this->htmlAttributes[HTML_ATTR_ID] = $hrefName . "_" . $this->attributes[FE_ID];
        $this->instantiateChildren();
    }

    /**
     * Pill FE's need both name and label set!
     *
     * @return void
     * @throws \CodeException
     * @throws \UserFormException
     */
    protected function handleEmptyNameOrLabel(): void {
        if ($this->attributes[FE_NAME] === '' || $this->attributes[FE_LABEL] === '') {
            $this->store->setVar(SYSTEM_FORM_ELEMENT, Logger::formatFormElementName($this->attributes), STORE_SYSTEM);
            $this->store->setVar(SYSTEM_FORM_ELEMENT_COLUMN, 'name, label', STORE_SYSTEM);
            throw new \UserFormException("Field 'name' and 'label' are empty", ERROR_NAME_LABEL_EMPTY);
        }
    }

    /**
     * Overwrite this method because pill children are picked slightly differently
     *
     * @return void
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    protected function instantiateChildren(): void {
        if ($this->form == null) return;
        $formElementAttributes = $this->databaseManager->getQfqDb()->getNativeFormElements(SQL_FORM_ELEMENT_SPECIFIC_CONTAINER, ['yes', $this->form->specFinal["id"], 'native,container', $this->attributes[FE_ID]], $this->form->specFinal);

        for ($i = 0; $i < count($formElementAttributes); $i++) {

            $tmpFE = array_merge($formElementAttributes[$i]);

            // Child FE inherits the pill's mode, but only if that mode has a higher priority
            // (hidden > readonly > required > show). E.g. a 'hidden' child is not downgraded to readonly.
            $childMode = $tmpFE[FE_MODE] ?? '';
            $combinedMode = Support::combineFeMode($this->attributes[FE_MODE], $childMode);
            if ($combinedMode !== $childMode) {
                $tmpFE[FE_MODE] = $combinedMode;
                $tmpFE[FE_MODE_SQL] = "";
            }

            $fe = FeFactory::createFormElement($tmpFE, $this->form);
            array_push($this->formElements, $fe);
        }
    }
}