<?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 PatientChartPaymentOtherProcedureForm 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('patientChartOtherProcedure', 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->getPatientChartOtherProcedure()->getNote() . ' - ' . $data->getPatientChartOtherProcedure()->getAmount(),
                    'data' => $data && $data->getId() > 0
                ));

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

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

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

    }

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

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