<?php

namespace RxConnexionBundle\Form\Type;

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

class ReferralServicesForm 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('service', HiddenType::class)
            ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {

            $form = $event->getForm();
            $data = $event->getData();

            $form
                ->add('is_checked', CheckboxType::class, array(
                    'mapped' => false,
                    'required' => false,
                    'label' => $data->getService()->getDescription(),
                    'data' => $data && $data->getId() > 0
                ));
            })
            ->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {

                $data = $event->getData();
                if(!isset($data['is_checked'])){
                $data['service'] = null;
                $event->setData($data);
                }

            });
        $builder->get('service')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ServiceEntity', false));

    }

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

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