<?php

namespace RxConnexionBundle\Form;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityRepository;
use RxConnexionBundle\Entity\AccountEntity;
use RxConnexionBundle\Entity\PatientEntity;
use RxConnexionBundle\Entity\ServiceEntity;
use RxConnexionBundle\Entity\SourceEntity;
use RxConnexionBundle\Form\Type\PatientServicesForm;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use RxConnexionBundle\Form\DataTransformer\DataTransformer;

class PatientForm extends AbstractType
{
    private $manager;

    public function __construct(ObjectManager $manager) {
        $this->manager = $manager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('action', HiddenType::class, array(
                'mapped' => false,
                'attr' => array(
                    'class' => 'form-action'
                )
            ))
            ->add('id', HiddenType::class)
            ->add('first_name', TextType::class, array(
                'label' => 'First Name',
                'label_attr' => array(
                    'class' => 'required middle'
                ),
                'required' => true
            ))
            ->add('middle_name', TextType::class, array(
                'label' => 'Middle Name',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('last_name', TextType::class, array(
                'label' => 'Last Name',
                'label_attr' => array(
                    'class' => 'required middle'
                ),
                'required' => true
            ))
            ->add('street', TextType::class, array(
                'label' => 'Street',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('personal_health_no', TextType::class, array(
                'label' => 'PHN',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('personal_health_no', TextType::class, array(
                'label' => 'PHN',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('mobile_no', TextType::class, array(
                'label' => 'Mobile No(s).',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('mobile_no_two', TextType::class, array(
                'label' => 'Mobile No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('mobile_no_three', TextType::class, array(
                'label' => 'Mobile No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('phone_no', TextType::class, array(
                'label' => 'Phone No(s).',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('phone_no_two', TextType::class, array(
                'label' => 'Phone No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('phone_no_three', TextType::class, array(
                'label' => 'Phone No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('email', TextType::class, array(
                'label' => 'Email(s)',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('email_two', TextType::class, array(
                'label' => 'Email',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('email_three', TextType::class, array(
                'label' => 'Email',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('gender', ChoiceType::class, array(
                'label' => 'Gender',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false,
                'choices' => array(
                    '' => '',
                    PatientEntity::GENDER_MALE => 'Male',
                    PatientEntity::GENDER_FEMALE => 'Female',
                )
            ))
            ->add('source', EntityType::class, array(
                'class' => SourceEntity::class,
                'choice_label' => 'description',
                'query_builder' => function(EntityRepository $er) use ($options) {

                    return $er->createQueryBuilder('cs')
                        ->orderBy('cs.description', 'ASC');
                },
                'label' => 'Source',
                'label_attr' => array(
                    'class' => 'required'
                ),
                'required' => true
            ))
            /*->add('account', HiddenType::class, array(
                'data' =>
            ))*/
            ->add('city', HiddenType::class)
            ->add('patient_type', HiddenType::class)
            ->add('postalCode', HiddenType::class)
            ->add('geo_lat', TextType::class, array(
                'label' => 'Latitude',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('account', EntityType::class, array(
                'class' => AccountEntity::class,
                'choice_label' => 'description',
                'query_builder' => function(EntityRepository $er) use ($options) {

                    return $er->createQueryBuilder('cs')
                        ->orderBy('cs.description', 'ASC');
                },
                'label' => 'Account',
                'label_attr' => array(
                    'class' => 'required'
                ),
                'required' => true
            ))
//            ->add('patient_services', EntityType::class, array(
//                'class' => ServicesEntity::class,
//                'choice_label' => 'description',
//                'multiple' => true,
//                'expanded' => true,
//                'query_builder' => function(EntityRepository $er) use ($options) {
//
//                    return $er->createQueryBuilder('s')
//                        ->orderBy('s.description', 'ASC');
//                },
//                'label' => 'Services',
//                'label_attr' => array(
//                    'class' => 'required'
//                ),
//                'required' => true
//            ))
            ->add('patientServices', CollectionType::class, array(
                'entry_type' => PatientServicesForm::class,
                'allow_add' => true,
                'allow_delete' => true,
                'prototype' => false,
                'by_reference' => false,
                'required' => false,
                'delete_empty' => function($patientService = null){
                    return !$patientService->getService();
                }

            ))
            ->add('geo_long', TextType::class, array(
                'label' => 'Longitude',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            /*->add('alberta_health_card_no', TextType::class, array(
                'label' => 'Alberta Health Card No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))*/
            ->add('personal_health_no', TextType::class, array(
                'label' => 'Personal Health No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false,

            ))
            ->add('referred_by_name', TextType::class, array(
                'label' => 'Referred By',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('is_test_patient', CheckboxType::class, array(
                'label' => 'Test Patient',
                'required' => false
            ))
            ->add('is_endorsed', CheckboxType::class, array(
                'label' => 'Endorsed',
                'required' => false
            ))
            ->add('is_specialist', CheckboxType::class, array(
                'label' => 'Specialist',
                'required' => false
            ))
            ->add('is_referral', CheckboxType::class, array(
                'label' => 'Referral',
                'required' => false,
                'mapped' => false
            ))
            ->add('isNotCountAsReferral', CheckboxType::class, array(
                'label' => 'Not Count As Referral',
                'required' => false
            ))
            ->add('endorsed_by', TextType::class, array(
                'label' => 'Endorsed To',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('is_active', CheckboxType::class, array(
                'label' => 'Active',
                'required' => false
            ))
            ->add('is_duplicate', CheckboxType::class, array(
                'label' => 'Duplicate',
                'required' => false
            ))
            /*->add('health_facility', HiddenType::class)*/
            ->add('primary_provider', HiddenType::class)
            ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {

                $form = $event->getForm();
                $data = $event->getData();
                $city = $data->getCity();
                $patientType = $data->getPatientType();
                $primaryProvider = $data->getPrimaryProvider();
                $postalCode = $data->getPostalCode();
                /*$healthFacility = $data->getHealthFacility();*/
                $referral = $data->getReferral();
                $faxTran = $referral ? $referral->getFaxTran() : '';

                $referredByPatient = '';
                if ($data->getReferredByPatient()) {
                    $referredByPatient = $data->getReferredByPatient()->getReferredByFullName();
                }

                $faxTranDate = '';
                if($faxTran != '' || $faxTran != null){
                    $faxTranDate = $faxTran->getFaxDateAsString();
                }
                $activeHealthFacility = '';
                if($data->getActivePatientHealthFacility()){
                    if($data->getActivePatientHealthFacility()->getHealthFacility()){
                        $activeHealthFacility = $data->getActivePatientHealthFacility()->getHealthFacility();
                    }
                }
                $form
                    ->add('patient_type_desc', TextType::class, array(
                        'label' => 'Type',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'required' => false,
                        'mapped' => false,
                        'data' => $patientType ? $patientType->getDescription() : ''
                    ))
                    ->add('referral_date', TextType::class, array(
                        'label' => 'Referral Date',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date',
                        ),
                        'data' => $data ? $data->getReferralDateAsString() : ''
                    ))
                    ->add('received_date', TextType::class, array(
                        'label' => 'Received Date',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date',
                        ),
                        'data' => $data ? ($data->getReceivedDateAsString() == '' || $data->getReceivedDateAsString() == null ? $faxTranDate : $data->getReceivedDateAsString()) : ''
                    ))
                    ->add('city_desc', TextType::class, array(
                        'label' => 'City',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $city ? $city->getDescription() : ''
                    ))
                    ->add('postalCode_desc', TextType::class, array(
                        'label' => 'Postal Code',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $postalCode ? $postalCode->getDescription() : ''
                    ))
                    ->add('birth_date', TextType::class, array(
                        'label' => 'Birth Date',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date'
                        ),
                        'data' => $data ? $data->getBirthDateAsString() : ''
                    ))
                    ->add('primary_provider_fullName', TextType::class, array(
                        'label' => 'Primary Clinician',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'required' => false,
                        'mapped' => false,
                        'data' => $primaryProvider ? $primaryProvider->getFullName() : ''
                    ))
                    ->add('health_facility', HiddenType::class, array(
                        'mapped' => false,
                        'data' => $activeHealthFacility ? $activeHealthFacility->getId() : ''
                    ))
                    ->add('health_facility_desc', TextType::class, array(
                        'label' => 'Branch',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $activeHealthFacility ? $activeHealthFacility->getDescription() : ''
                    ))
                    ->add('referredBy', HiddenType::class, array(
                        'mapped' => false,
                    ))
                    ->add('referredByPatient_fullName', TextType::class, array(
                        'label' => 'Referred By',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'mapped' => false,
                        'required' => false,
                        'data' => $referredByPatient ? $referredByPatient : '',
                    ));
            });

        $builder->get('city')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:CityEntity', false));
        $builder->get('postalCode')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:PostalCodeEntity', false));
        $builder->get('patient_type')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:PatientTypeEntity', false));
        $builder->get('primary_provider')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ProviderEntity', false));
        /*$builder->get('health_facility')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:HealthFacilityEntity', false));*/
//        $builder->get('referral')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ReferralEntity', false));
    }

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

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' 	  => 'RxConnexionBundle\Entity\PatientEntity',
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            // a unique key to help generate the secret token
            'intention'       => 'patientEntity_intention',
            'action'          => 'n'
        ));
    }
}