<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers;

use TYPO3\CMS\Fluid\ViewHelpers\Form\AbstractFormViewHelper;
use Stringable;

/**
 * Provides an interface for aggregators like tabs and fieldsets
 */
class AbstractAggregateViewHelper extends AbstractFormViewHelper implements AggregateInterface, Stringable
{
    /**
     * Add an aggregate to the collection
     *
     * @param  Internetgalerie\IgDatapoolFe\ViewHelpers\Aggregate $agg
     * @return void
     */
    public function addAggregate(AggregateInterface $agg): void
    {
        $this->children[] = $agg;
    }

    /**
     * Check children for errorous fields
     *
     * @return bool;
     */
    public function hasError()
    {
        $error = false;
        if (isset($this->children) && count($this->children)) {
            foreach ($this->children as $child) {
                if ($child->hasError()) {
                    $error = true;
                }
            }
        }
        return $error;
    }

    /**
     * Renders teh aggregates content and sets the context accordingly
     */
    public function renderAggregateChildren()
    {
        $last = FormViewHelper::$curAggregate;
        FormViewHelper::$curAggregate = $this;
        $out = $this->renderChildren();
        FormViewHelper::$curAggregate = $last;
        return $out;
    }

    /**
     * When rendering, add this aggregate to the parent
     * Thsi method should be called in each aggregates render() method
     */
    public function render(): string
    {
        if (FormViewHelper::$curAggregate) {
            //   FormViewHelper::$curAggregate->addAggregate($this);
        }
    }

    /**
     * For debugging purpose..
     */
    public function __toString(): string
    {
        $out = '';
        foreach ($this->children as $t) {
            $out .= $t;
        }
        return '<br /><br /><strong>' . static::class . ' ' . spl_object_hash($this) . '</strong><br /><div style="padding-left:20px;border:1px solid green;margin-bottom:20px;">chindlren:<br />' . $out . '</div>';
    }
}
