<?php

namespace RxConnexionBundle\Form;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityRepository;
use RxConnexionBundle\Entity\ChartTypeEntity;
use RxConnexionBundle\Entity\PatientNoteEntity;
use RxConnexionBundle\Entity\ProviderEntity;
use RxConnexionBundle\Entity\ScheduleEntity;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use RxConnexionBundle\Entity\ScheduleStatusEntity;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
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 ScheduleForCalendarForm 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('provider', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['provider_id']
                )
            ))
            ->add('health_facility', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['healthFacility_id']
                )
            ))
            ->add('patient_city_id', HiddenType::class, array(
                'mapped' => false
            ))
            ->add('start_time', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['startTime']
                )

            ))
            /*->add('start_time_period', HiddenType::class, array(

            ))*/
            ->add('start_time_minute', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['startTimeMin']
                )
            ))
            ->add('start_time_hour', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['startTimeHour']
                )
            ))
            ->add('id', HiddenType::class)
            ->add('note', TextareaType::class, array(
                'label' => 'Notes',
                'label_attr' => array(
                    'class' => 'required middle'
                ),
                'required' => true,
                'attr' => array(
                    'rows' => 5
                ),
                'data' => null
            ))
            ->add('end_time_period', ChoiceType::class, array(
                'required' => true,
                'choices' => array(
                    ScheduleEntity::END_TIME_PERIOD_AM => 'AM',
                    ScheduleEntity::END_TIME_PERIOD_PM => 'PM'
                ),
                'data' => $options['startTimeHour'] == 11 && ($options['startTimeMin'] >= 30) ? 'PM' : $options['startTimePeriod']
            ))
            /*->add('chart_type', EntityType::class, array(
                'class' => ChartTypeEntity::class,
                'choice_label' => 'description',
                'query_builder' => function(EntityRepository $er) {

                    return $er->createQueryBuilder('ct')
                        ->where('ct.isActive = 1')
                        ->orderBy('ct.description', 'ASC');
                },
                'label' => 'Chart Type',
                'label_attr' => array(
                    'class' => 'required'
                ),
                'required' => false
            ))*/
            ->add('start_time_hour', ChoiceType::class, array(
                'required' => true,
                'choices' => $this->generateHoursArray(),
                'data' => $options['startTimeHour']
            ))
            ->add('start_time_minute', ChoiceType::class, array(
                'required' => true,
                'choices' => $this->generateMinutesArray(),
                'data' => $options['startTimeMin']
            ))
            ->add('start_time_period', ChoiceType::class, array(
                'required' => true,
                'choices' => array(
                    ScheduleEntity::START_TIME_PERIOD_AM => 'AM',
                    ScheduleEntity::START_TIME_PERIOD_PM => 'PM'
                ),
                'data' => $options['startTimePeriod']
            ))
            ->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')
                        ->andWhere('ss.isDeleted = 0')
                        ->orderBy('ss.description', 'ASC');
                },
                'label' => 'Appointment 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('patient', HiddenType::class)
            ->add('chartType', HiddenType::class)
            ->add('noteTemplate', HiddenType::class)
            ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) use ($options) {

                $form = $event->getForm();
                $data = $event->getData();
                $patient = $data->getPatient();
                $provider = $data->getProvider();
                $healthFacility = $data->getHealthFacility();
                $chartType = $data->getChartType();
                $noteTemplate = $data->getNoteTemplate();
                $form
                    ->add('patient_fullName', TextType::class, array(
                        'label' => 'Patient',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $patient ? $patient->getFullName() : ''
                    ))
                    ->add('provider_fullName', TextType::class, array(
                        'label' => 'Clinician',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $provider ? $provider->getFullName() : $options['providerFullName']
                    ))
                    ->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() :  $options['healthFacilityName']
                    ))
                    ->add('schedule_date', TextType::class, array(
                        'label' => 'Appt. Date',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date'
                        ),
                        'data' =>  $data->getScheduleDateAsString() ? $data->getScheduleDateAsString() : $options['schedDate']
                    ))
                    ->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() : ''
                    ))
                    ->add('patient_geoLat', HiddenType::class, array(
                        'attr' => array(
                            'value' => $patient ? $patient->getGeoLat() : ''
                        ),
                        'mapped' => false
                    ))
                    ->add('patient_geoLong', HiddenType::class, array(
                        'attr' => array(
                            'value' => $patient ? $patient->getGeoLong() : ''
                        ),
                        'mapped' => false
                    ))
                    ->add('health_facility_city_id', HiddenType::class, array(
                        'attr' => array(
                            'value' => $healthFacility ? $healthFacility->getId() : $options['healthFacility_city_id']
                        ),
                        'mapped' => false
                    ))
                    ->add('health_facility_geoLat', HiddenType::class, array(
                        'attr' => array(
                            'value' => $healthFacility ? $healthFacility->getGeoLatitude() : $options['healthFacility_geoLat']
                        ),
                        'mapped' => false
                    ))
                    ->add('health_facility_geoLong', HiddenType::class, array(
                        'attr' => array(
                            'value' => $healthFacility ? $healthFacility->getGeoLongitude() : $options['healthFacility_geoLong']
                        ),
                        'mapped' => false
                    ));
            });
            if($options['action'] == 'n'){
                if($options['startTimeMin'] === '30'){
                    $builder
                        ->add('end_time_hour', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateHoursArray(),
                            'data' => $options['startTimeHour'] + 1
                        ))
                        ->add('end_time_minute', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateMinutesArray(),
                            'data' => '00'
                        ));
                }elseif($options['startTimeMin'] === '45'){
                    $builder
                        ->add('end_time_hour', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateHoursArray(),
                            'data' => $options['startTimeHour'] + 1
                        ))
                        ->add('end_time_minute', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateMinutesArray(),
                            'data' => '15'
                        ));
                }else{
                    $builder
                        ->add('end_time_hour', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateHoursArray(),
                            'data' => $options['startTimeHour']
                        ))
                        ->add('end_time_minute', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateMinutesArray(),
                            'data' => $options['startTimeMin'] + 30
                        ));
                }
            }else{
                $builder
                    ->add('end_time_hour', ChoiceType::class, array(
                        'required' => true,
                        'choices' => $this->generateHoursArray()
                    ))
                    ->add('end_time_minute', ChoiceType::class, array(
                        'required' => true,
                        'choices' => $this->generateMinutesArray()
                    ));
            }

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

    public function getBlockPrefix()
    {
        return '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',
            'healthFacility_id' => null,
            'provider_id'     => null,
            'schedDate'       => null,
            'startTime'       => null,
            'startTimeHour'       => null,
            'startTimeMin'       => null,
            'startTimePeriod'       => null,
            'providerFullName'    => null,
            'healthFacilityName'  => null,
            'healthFacility_city_id' => null,
            'healthFacility_geoLat' => null,
            'healthFacility_geoLong' => 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;
    }

}