<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Form\Type\Export;

use Chill\MainBundle\Export\DataTransformerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class AggregatorType extends AbstractType
{
    public const ENABLED_FIELD = 'enabled';

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $exportManager = $options['export_manager'];
        $aggregator = $exportManager->getAggregator($options['aggregator_alias']);

        $builder
            ->add(self::ENABLED_FIELD, CheckboxType::class, [
                'value' => true,
                'required' => false,
                'disabled' => $options['disable_enable_field'],
            ]);

        $aggregatorFormBuilder = $builder->create('form', FormType::class, [
            'compound' => true,
            'required' => false,
            'error_bubbling' => false,
        ]);
        $aggregator->buildForm($aggregatorFormBuilder);

        if ($aggregator instanceof DataTransformerInterface) {
            $aggregatorFormBuilder->addViewTransformer(new CallbackTransformer(
                fn (?array $data) => $data,
                fn (?array $data) => $aggregator->transformData($data),
            ));
        }

        $builder->add($aggregatorFormBuilder);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setRequired('aggregator_alias')
            ->setRequired('export_manager')
            ->setDefault('disable_enable_field', false)
            ->setDefault('compound', true)
            ->setDefault('error_bubbling', false);
    }
}
