<?php

/*
 * This file is part of the Serenity package.
 *
 * (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\SocialNetwork;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ConnectFacebookInstagramIdType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ConnectFacebookUserIdType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\DataTransformer\JsonModelTransformerFactory;
use CpCreation\VitiCore\SocialNetwork\Model\Network\FacebookInstagram;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class FacebookInstagramNetworkType extends AbstractType implements SocialNetworkNetworkInterface
{
    public const TYPE = 'facebook_instagram';

    public function __construct(
        private readonly JsonModelTransformerFactory $transformers,
    ) {
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('id', ConnectFacebookUserIdType::class, [
                'label' => 'Connect Client Social ID',
                'required' => true,
            ])
            ->add('accountInstagram', ConnectFacebookInstagramIdType::class)
            ->add('name', HiddenType::class);

        $builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'onPreSubmit']);

        $builder->addModelTransformer(
            $this->transformers->for(FacebookInstagram::class)
        );
    }

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

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

        if (!\is_array($data) || !isset($data['accountInstagram'])) {
            return;
        }

        $normData = $form->getNormData();
        $userId = \is_object($normData) && method_exists($normData, 'getId') ? $normData->getId() : null;

        if (!$userId) {
            return;
        }

        $choices = (array) $form->get('accountInstagram')->getConfig()->getOption('choices');

        foreach ($choices as $key => $choice) {
            if ($choice === $data['accountInstagram']) {
                $data['name'] = $key;
                break;
            }
        }

        $event->setData($data);
    }

    public function getNetwork(): string
    {
        return self::TYPE;
    }

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