<?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\DocGeneratorBundle\Form;

use Chill\DocGeneratorBundle\Context\ContextManager;
use Chill\DocGeneratorBundle\Context\DocGeneratorContextWithAdminFormInterface;
use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
use Chill\DocStoreBundle\Form\StoredObjectType;
use Chill\MainBundle\Form\Type\TranslatableStringFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class DocGeneratorTemplateType extends AbstractType
{
    public function __construct(private readonly ContextManager $contextManager) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        /** @var DocGeneratorTemplate $template */
        $template = $options['data'];
        $context = $this->contextManager->getContextByKey($template->getContext());

        $builder
            ->add('name', TranslatableStringFormType::class, [
                'label' => 'Nom',
            ])
            ->add('description')
            ->add('file', StoredObjectType::class, [
                'error_bubbling' => true,
            ])
            ->add('active', ChoiceType::class, [
                'label' => 'Active',
                'choices' => [
                    'Yes' => true,
                    'No' => false,
                ],
                'required' => true,
            ]);

        if (
            $context instanceof DocGeneratorContextWithAdminFormInterface
            && $context->hasAdminForm()
        ) {
            $sub = $builder
                ->create('options', null, ['compound' => true])
                ->addModelTransformer(new CallbackTransformer(
                    static fn (array $data) => $context->adminFormTransform($data),
                    static fn (array $data) => $context->adminFormReverseTransform($data)
                ));
            $context->buildAdminForm($sub);
            $builder->add($sub);
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefault('class', DocGeneratorTemplate::class);
    }
}
