<?php

namespace RxConnexionBundle\Form;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityRepository;
use RxConnexionBundle\Entity\ChartTypeEntity;
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 ScheduleForm 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('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' => 'middle'
                ),
                'required' => false,
                'attr' => array(
                    'rows' => 5
                )
            ))
            ->add('schedule_status', EntityType::class, array(
                'class' => ScheduleStatusEntity::class,
                'choice_label' => 'description',
                'query_builder' => function(EntityRepository $er) use ($options) {

                    return $er->createQueryBuilder('ss')
                        ->orderBy('ss.description', 'ASC');
                },
                'label' => 'Status',
                'label_attr' => array(
                    'class' => 'required'
                ),
                'required' => true
            ))
            ->add('chart_type', EntityType::class, array(
                'class' => ChartTypeEntity::class,
                'choice_label' => 'description',
                'query_builder' => function(EntityRepository $er) use ($options) {

                    return $er->createQueryBuilder('ct')
                        ->orderBy('ct.description', 'ASC');
                },
                'label' => 'Chart Type',
                'label_attr' => array(
                    'class' => 'required'
                ),
                'required' => true
            ))
            ->add('health_facility', HiddenType::class)
            ->add('patient', HiddenType::class)
            ->add('provider', HiddenType::class)
            ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {

                $form = $event->getForm();
                $data = $event->getData();
                $healthFacility = $data->getHealthFacility();
                $patient = $data->getPatient();
                $provider = $data->getProvider();

                $form
                    ->add('health_facility_desc', TextType::class, array(
                        'label' => 'Branch',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $healthFacility ? $healthFacility->getDescription() : ''
                    ))
                    ->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' => 'Provider',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $provider ? $provider->getFullName() : ''
                    ))
                    ->add('schedule_date', TextType::class, array(
                        'label' => 'Appointment Date',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date'
                        ),
                        'data' => $data ? $data->getScheduleDateAsString() : ''
                    ));
            });

        $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('chart_type')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ChartTypeEntity', false));
        $builder->get('schedule_status')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ScheduleStatusEntity', 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'
        ));
    }

    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;
    }
}