<?php

/*
 * This file is part of the VitiCore 2.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Manager\SocialNetworkNetworkManager;
use CpCreation\VitiCore\SocialNetwork\Model\SocialNetwork;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class SocialNetworkStep2Type extends AbstractType
{
    public function __construct(
        private readonly SocialNetworkNetworkManager $manager,
    ) {
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'onPreSetData']);
    }

    public function onPreSetData(FormEvent $event): void
    {
        $data = $event->getData();

        if (!$data instanceof SocialNetwork) {
            return;
        }

        $network = $data->getNetwork();
        if (null === $network || '' === $network) {
            return;
        }

        $type = $this->manager->createFormSocialNetworkManager($network);

        // Symfony 7: idéalement $type === FQCN (string)
        $fieldType = \is_string($type)
            ? $type
            : (method_exists($type, 'getName') ? $type->getName() : null);

        if (null === $fieldType) {
            return;
        }

        $form = $event->getForm();

        if ($form->has('configuration')) {
            $form->remove('configuration');
        }

        $form->add('configuration', $fieldType, [
            'label' => false,
            'required' => true,
        ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => SocialNetwork::class,
        ]);
    }

    public function getBlockPrefix(): string
    {
        return 'social_network_step2';
    }
}
