<?php

namespace IMATHUZH\Qfq\Core\Form\FormElement;

use IMATHUZH\Qfq\Core\Form\FeFactory;
use IMATHUZH\Qfq\Core\Form\Form;

/**
 * A FormElement that contains other FormElements (children).
 * Children are automatically loaded, instantiated and stored in $this->formElements when the ContainerFormElement is instantiated.
 */
class ContainerFormElement extends AbstractFormElement {
    /**
     * @var array $formElements Child Elements of this Container.
     * @var ?Form $form
     * @var bool $instantiateChildren Instantiation of children can be prevented by setting this to false.
     */
    public array $formElements = array();

    /**
     * @param $attributes
     * @param Form|null $form
     * @param $instantiateChildren
     * @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, $instantiateChildren = true) {
        parent::__construct($attributes, $form);
        if ($instantiateChildren) $this->instantiateChildren();
    }

    /**
     * Fetches all children of this container FE from the database and instantiates an object for each of them.
     * Stores the children in $formElements. May be overridden by specific classes to match requirements
     *
     * @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, ['no', $this->form->specFinal["id"], 'native,container', $this->attributes[FE_ID]], $this->form->specFinal);

        for ($i = 0; $i < count($formElementAttributes); $i++) {
            $fe = FeFactory::createFormElement($formElementAttributes[$i], $this->form);
            array_push($this->formElements, $fe);
        }
    }
}