<?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 PatientChartPaymentProcedureForm 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('patientChartProcedure', 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->getPatientChartProcedure()->getChartProcedure()->getDescription() . ' - ' . $data->getPatientChartProcedure()->getAmount(),
                    'data' => $data && $data->getId() > 0
                ));

        })
            ->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {

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

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

    }

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

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