<?php
/**
 * @author Colinet Julien
 */

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ConnectFacebookFacebookIdType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ConnectFacebookUserIdType;
use CpCreation\VitiCore\SocialNetwork\Model\Network\FacebookFacebook;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
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;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class FacebookFacebookNetworkType extends AbstractType implements SocialNetworkNetworkInterface, DataTransformerInterface
{
    const TYPE = 'facebook_facebook';

    /**
     * @var Serializer
     */
    private $serializer;


    public function __construct()
    {
        $normalizers      = [new ObjectNormalizer()];
        $this->serializer = new Serializer($normalizers);
    }

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

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

        $builder->addModelTransformer($this);
    }

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


    public function onPreSubmit(FormEvent $event)
    {
        $form = $event->getForm();
        $data = $event->getData();
        $userId       = $form->getNormData()->getId();
        if ($userId) {
            foreach ($form->get('accountFacebook')->getConfig()->getOption('choices') as  $key => $choice)
            {
                if ($choice == $data['accountFacebook'])
                {
                    $data['name'] = $key;
                }
            }
            $event->setData($data);
        }
    }

    public function transform($data)
    {

        return $this->serializer->denormalize($data, FacebookFacebook::class);
    }

    public function reverseTransform($data)
    {

        return $this->serializer->normalize($data);
    }

    public function getNetwork()
    {
        return static::TYPE;
    }

    public function getBlockPrefix()
    {
        return 'facebook_facebook_network';
    }
}