<?php

namespace RxConnexionBundle\Form\Type;

use Doctrine\Common\Persistence\ObjectManager;
use RxConnexionBundle\Form\DataTransformer\DataTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ChatParticipantFormType extends AbstractType
{
    private $manager;

    public function __construct(ObjectManager $manager) {
        $this->manager = $manager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id', HiddenType::class)
            ->add('account_user', HiddenType::class, array(
                'required' => false,
            ))
            ->addEventListener(FormEvents::PRE_SET_DATA,function (FormEvent $event) use ($builder) {
                $form = $event->getForm();
                $data = $event->getData();
                $accountUser = $data ? $data->getAccountUser() : false;
                $form
                    ->add('account_user_name', TextType::class, array(
                        'mapped' => false,
                        'required' => true,
                        'data' => $accountUser ? $accountUser->getFullName() : ''
                    ));
            });
        $builder->get('account_user')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:AccountUserEntity', false));

    }

    public function getName()
    {
        return 'chatParticipant';
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' 	  => 'RxConnexionBundle\Entity\ChatParticipantEntity',
        ));
    }
}