<?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 Chill\MainBundle\Export\FilterInterface;
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 FilterType extends AbstractType
{
    final public const ENABLED_FIELD = 'enabled';

    public function __construct() {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $filter = $options['filter'];

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

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

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

        $builder->add($filterFormBuilder);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setRequired('filter')
            ->setAllowedTypes('filter', [FilterInterface::class])
            ->setDefault('disable_enable_field', false)
            ->setDefault('compound', true)
            ->setDefault('error_bubbling', false);
    }
}
