<?php

namespace RxConnexionBundle\Form;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityRepository;
use RxConnexionBundle\Entity\ChartTypeEntity;
use RxConnexionBundle\Entity\PatientNoteEntity;
use RxConnexionBundle\Entity\ScheduleEntity;
use RxConnexionBundle\Entity\ScheduleStatusEntity;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
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 PatientScheduleForm 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('patient', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['patient_id']
                )
            ))
            ->add('id', HiddenType::class)
            ->add('start_time_hour', ChoiceType::class, array(
                'required' => true,
                'choices' => $this->generateHoursArray()
            ))
            ->add('start_time_minute', ChoiceType::class, array(
                'required' => true,
                'choices' => $this->generateMinutesArray()
            ))
            ->add('start_time_period', ChoiceType::class, array(
                'required' => true,
                'choices' => array(
                    ScheduleEntity::START_TIME_PERIOD_AM => 'AM',
                    ScheduleEntity::START_TIME_PERIOD_PM=> 'PM'
                )
            ))
            ->add('end_time_hour', ChoiceType::class, array(
                'required' => true,
                'choices' => $this->generateHoursArray()
            ))
            ->add('end_time_minute', ChoiceType::class, array(
                'required' => true,
                'choices' => $this->generateMinutesArray()
            ))
            ->add('end_time_period', ChoiceType::class, array(
                'required' => true,
                'choices' => array(
                    ScheduleEntity::END_TIME_PERIOD_AM => 'AM',
                    ScheduleEntity::END_TIME_PERIOD_PM => 'PM'
                )
            ))
            ->add('note', TextareaType::class, array(
                'label' => 'Notes',
                'label_attr' => array(
                    'class' => 'required middle'
                ),
                'required' => true,
                'attr' => array(
                    'rows' => 5
                ),
                'data' => null
            ))
            ->add('scheduleStatus', EntityType::class, array(
                'class' => ScheduleStatusEntity::class,
                'choice_label' => 'description',
                'query_builder' => function(EntityRepository $er) use ($options) {

                    return $er->createQueryBuilder('ss')
                        ->where('ss.isActive = 1')
                        ->orderBy('ss.description', 'ASC');
                },
                'label' => 'Status',
                'label_attr' => array(
                    'class' => 'required'
                ),
                'required' => true
            ))
            ->add('note_type', ChoiceType::class, array(
                'label' => 'Note Type',
                'required' => false,
                'choices' => array(
                    PatientNoteEntity::TYPE_CLINICAL => 'Clinical',
                    PatientNoteEntity::TYPE_BILLING => 'Billing',
                    PatientNoteEntity::TYPE_APPOINTMENT => 'Appointment',
                    PatientNoteEntity::TYPE_TEMPLATE => 'Template',
                ),
                'mapped' => false
            ))/*            ->add('chart_type', EntityType::class, array(
                'class' => ChartTypeEntity::class,
                'choice_label' => 'description',
                'query_builder' => function(EntityRepository $er) use ($options) {

                    return $er->createQueryBuilder('ct')
                        ->where('ct.isActive = 1')
                        ->orderBy('ct.description', 'ASC');
                },
                'label' => 'Encounter Type',
                'label_attr' => array(
                    'class' => 'required'
                ),
                'required' => true
            ))*/
            ->add('health_facility', HiddenType::class)
            ->add('provider', HiddenType::class)
            ->add('chartType', HiddenType::class)
            ->add('noteTemplate', HiddenType::class)
            ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {

                $form = $event->getForm();
                $data = $event->getData();
                $healthFacility = $data->getHealthFacility();
                $provider = $data->getProvider();
                $faxCoverSelection = explode(',', $data->getFaxCoverSelection());
                $faxBodySelection = explode(',', $data->getFaxBodySelection());
                $chartType = $data->getChartType();
                $noteTemplate = $data->getNoteTemplate();

                $form
                    ->add('chartType_desc', TextType::class, array(
                        'label' => 'Type',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $chartType ? $chartType->getDescription() : ''
                    ))
                    ->add('health_facility_desc', TextType::class, array(
                        'label' => 'Branch',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $healthFacility ? $healthFacility->getDescription() : ''
                    ))
                    ->add('provider_fullName', TextType::class, array(
                        'label' => 'Clinician',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $provider ? $provider->getFullName() : ''
                    ))
                    ->add('schedule_date', TextType::class, array(
                        'label' => 'Schedule Date',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date'
                        ),
                        'data' => $data ? $data->getScheduleDateAsString() : ''
                    ))
                    ->add('faxCoverSelection', ChoiceType::class, array(
                        'required' => false,
                        'choices' => array(
                            'Urgent' => ScheduleEntity::FAX_COVER_SELECTION_1,
                            'For Review' => ScheduleEntity::FAX_COVER_SELECTION_2,
                            'Please Comment' => ScheduleEntity::FAX_COVER_SELECTION_3,
                            'Please Reply' => ScheduleEntity::FAX_COVER_SELECTION_4,
                        ),
                        'expanded' => true,
                        'multiple' => true,
                        'mapped' => false,
                        'data' => $faxCoverSelection
                    ))
                    ->add('faxBodySelection', ChoiceType::class, array(
                        'required' => false,
                        'choices' => array(
                            'Patient is aware of the appointment' => ScheduleEntity::FAX_BODY_SELECTION_1,
                            'Message left on the voicemail' => ScheduleEntity::FAX_BODY_SELECTION_2,
                            'Patient declined test' => ScheduleEntity::FAX_BODY_SELECTION_3,
                            'Patient is unable to contact. Please inform the patient of the appointment' => ScheduleEntity::FAX_BODY_SELECTION_4,
                            'Patient is on CPAP Trial/Evaluation.' => ScheduleEntity::FAX_BODY_SELECTION_5,
                        ),
                        'expanded' => true,
                        'multiple' => true,
                        'mapped' => false,
                        'data' => $faxBodySelection
                    ))
                    ->add('note_template_description', TextType::class, array(
                        'mapped' => false,
                        'label' => 'Note Template',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'required' => false,
                        'attr' => array(
                            'class' => 'hide'
                        ),
                        'data' => $noteTemplate ? $noteTemplate->getDescription() : ''
                    ));
            });

        $builder->get('health_facility')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:HealthFacilityEntity', false));
        $builder->get('patient')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:PatientEntity', true));
        $builder->get('provider')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ProviderEntity', false));
        $builder->get('chartType')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ChartTypeEntity', false));
        $builder->get('noteTemplate')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:NoteTemplateEntity', false));
    }

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

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

    private function generateHoursArray() {

        $hoursArray = array();

        for($i=1; $i<=12; $i++) {
            $hoursArray[sprintf('%002d', $i)] = $i;
        }
        return $hoursArray;

    }

    private function generateMinutesArray() {

        $minutesArray = array();

        for($i=0; $i<=55; $i+=5) {
            $minutesArray[sprintf('%002d', $i)] = $i;
        }

        return $minutesArray;
    }
}