<?php

namespace RxConnexionBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
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 Doctrine\Common\Persistence\ObjectManager;
use RxConnexionBundle\Form\DataTransformer\DataTransformer;

class PatientTicketForm 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('patient', HiddenType::class, array(
                'required' => false
            ))
            ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {

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

                $patient = $data ? $data->getPatient() : null;

                $form
                    ->add('patientTicket_patientName', TextType::class, array(
                        'mapped' => false,
                        'data' => $patient ? $patient->getId() : ''
                    ));
            });

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

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

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