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

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

                $patientChart = $data ? $data->getPatientChart() : null;

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

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

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

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