<?php

namespace OfficeBrain\Bundle\UserBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormTypeInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Validator\ExecutionContextInterface as context;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormError;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Validator\Constraints\Length; 

class ContactBookType extends AbstractType
{
    /**
     *
     * @param ContainerInterface $container
     * @param $mode
     */
    public function __construct(ContainerInterface $container, $side = '')
    {
        $this->container = $container;
        $this->side = $side;
        $this->request = $this->container->get('request');
        $this->projectUserSetting = $this->request->get('project_user_setting')['user_data'];
        $this->userId = $this->projectUserSetting->getId();
        $this->userConfigrationSetting = $this->request->get('project_setting')['configuration_rule']['user'];
        $this->contactSetting = $this->request->get('project_setting')['configuration_rule']['site_management']['option']['address']['option'];
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
    	if ($this->side == 'adminSide' || $this->side == 'myContactBook') {
    		$lengthParameters = $this->userConfigrationSetting['contact_book'];
    	}else{
    		$lengthParameters = $this->userConfigrationSetting['address_book'];
    	}    
        $addressTypemaster = $this->container->get('office_brain_user_contact_book_manager');
        $master = $this->container->get('office_brain_core_manager');
        $shippingType = array('1' => 'user.contact_book.shipping_type.office', '0' => 'user.contact_book.shipping_type.home');
        $countryConfiguration=array();
        foreach ($this->container->getParameter('country') as $key=>$value) {
            $countryConfiguration[]=$value['short_name'];
        }
        $country=$master->getCountryData($countryConfiguration);
        if ($builder->getData()->getCountryId() != "") {
            $state = $master->getStateData($builder->getData()->getCountryId());
        } else {
            $state = array();
        }
        if ($builder->getData()->getStateId() != "") {
            $city = $master->getCityData($builder->getData()->getStateId(), $builder->getData()->getCountryId());
        } else {
            $city = array();
        }

        if ($this->side == 'adminSide') {
            if ($this->userId) {
                $builder->add('user', 'entity', array(
                        'class' => 'OfficeBrainUserBundle:User',
                        'query_builder' => function (EntityRepository $er) {
                            return $er->createQueryBuilder('c')
                            ->where('c.createdUid ='.$this->userId)
                            ->andWhere('c.deletedAt is null')
                            ->andWhere("c.locked is NULL")
                            ->andWhere("c.expired is NULL")
                            ->andWhere("c.userType !='employee'")
                            ->andWhere("c.userType !='branchEmployee'")
                            ->orderBy('c.id', 'ASC');
                        },
                        'property' => 'firstName',
                        'placeholder' => 'select user',
                        'empty_data'  => null,
                        'constraints' => array(new Assert\NotBlank(array('message'=>'user.contact_book.user.not_blank'))),
                ));
            }else{
                $builder->add('user', 'entity', array(
                        'class' => 'OfficeBrainUserBundle:User',
                        'query_builder' => function (EntityRepository $er) {
                            return $er->createQueryBuilder('c')
                            ->andWhere('c.deletedAt is null')
                            ->andWhere("c.locked is NULL")
                            ->andWhere("c.expired is NULL")
                            ->andWhere("c.userType !='employee'")
                            ->andWhere("c.userType !='branchEmployee'")
                            ->orderBy('c.id', 'ASC');
                        },
                        'property' => 'firstName',
                        'placeholder' => 'select user',
                        'empty_data'  => null,
                        'constraints' => array(new Assert\NotBlank(array('message'=>'user.contact_book.user.not_blank'))),
                ));
            }
        }
        if ($this->side == 'adminSide' ||  $this->side == 'myContactBook') {
            $builder->add('companyName', 'text', array(
                	    'required' => false,
            			'constraints'=>array( new Assert\Length(array('max'=>$lengthParameters['max_length_companyname'], 'maxMessage'=>'user.contact_book.companyName.max_length')))
            		))
            		->add('companyNumber', 'text', array(
		                 'required' => false,
            			 'constraints'=>array( new Assert\Length(array('max'=>$lengthParameters['max_length_companynumber'], 'maxMessage'=>'user.contact_book.companyNumber.max_length')))
        		    ));
        }else{
        	$builder->add('companyName', 'text', array(
        			'required' => false,
        			'constraints'=>array(new Assert\Length(array('max'=>$lengthParameters['max_length_companyname'], 'maxMessage'=>'user.contact_book.companyName.max_length')))
        	));
        }
        $builder
            ->add('name', 'text', array(
                    'required' => false,
            		'constraints'=>array( new Assert\Length(array('max'=>$lengthParameters['max_length_name'], 'maxMessage'=>'user.contact_book.name.max_length')))
            ))
            ->add('adressType', 'entity', array(
                    'class' => 'OfficeBrainCoreBundle:AddressType',
                    'query_builder' => function (EntityRepository $er) {
                        return $er->createQueryBuilder('a')
                        ->orderBy('a.id', 'ASC');
                    },
                    'property' => 'name',
                    'placeholder' => 'Select Address Type',
                    'empty_data'  => null,
            ))      
            ->add('email', 'text')
            ->add('street1', 'text')
            ->add('street2', 'text');
            if($this->contactSetting['country']['option']['textbox']['status']==1){
				$builder
				->add('countryId', 'choice', array(
						'choices'=> $country,
						'empty_value'=>  'user.contact_book.countryId.select_value',
				))
				->add('countryName', 'text', array(
						'required' => false,
						'constraints' => array(new Assert\NotBlank(array('message'=>'user.contact_book.countryName.not_blank'))),
				));
			}
			if($this->contactSetting['country']['option']['dropdown']['status']==1){
				$builder
				->add('countryId', 'choice', array(
						'choices'=> $country,
						'data'=>233,
						'empty_value'=>  'user.contact_book.countryId.select_value',
				))
				->add('countryName', 'text', array(
						'required' => false,
						
				));
			}
			if($this->contactSetting['state']['option']['textbox']['status']==1){
				$builder
				->add('stateId', 'choice', array(
						'choices'=> $state,
						'placeholder' => 'user.contact_book.stateId.select_value',
								'empty_data'  => null,
				))
				->add('stateName', 'text', array(
						'required' => false,
						'constraints' => array(new Assert\NotBlank(array('message'=>'user.contact_book.stateName.not_blank'))),
				));
			}
			
			if($this->contactSetting['state']['option']['dropdown']['status']==1){
				$builder
				->add('stateId', 'choice', array(
						'choices'=> $state,
						'placeholder' => 'user.contact_book.stateId.select_value',
								'empty_data'  => null,
				))
				->add('stateName', 'text', array(
						'required' => false,
				));
			}
			$builder
            ->add('cityId', 'choice', array(
                    'choices'=> $city,
                    'placeholder' => 'user.contact_book.cityId.select_value',
                     'empty_data'  => null,
            ))
            ->add('cityName', 'text', array(
            		'required' => false,
            		'constraints' => array(new Assert\NotBlank(array('message'=>'user.contact_book.cityName.not_blank'))),
            ))

            ->add('zipcode', 'text')
            ->add('extension', 'text')
            ->add('phone', 'text', array(
                    'required' => true,
            		'constraints'=>array( new Assert\Length(array('min' => 12,'max' => 12, 'exactMessage' => 'user.phone.invalid')))
            ))
            ->add('mobile', 'text', array(
                    'required' => false,
            		'constraints'=>array( new Assert\Length(array('min' => 12,'max' => 12, 'exactMessage' => 'user.mobile.invalid')))
            ))
            ->add('fax', 'text', array(
                    'required' => true,
            		'constraints'=>array( new Assert\Length(array('min' => 12,'max' => 12, 'exactMessage' => 'user.fax.invalid')))
            ))
            ->add('website', 'text', array(
                    'required' => false,
            		'constraints'=>array( new Assert\Length(array('max'=>$lengthParameters['max_length_website'], 'maxMessage'=>'user.contact_book.website.max_length')))
            ))
            ->add('isOffice', 'choice', array(
            		'choices' => $shippingType,
            		'multiple'=>false,
            		'expanded' => true,
            ))
            ->add('isAddress', 'hidden')
            ->add('erpId', 'hidden')
            ;

        $formModifier1 = function (FormInterface $form, $state) {
                    $form->add('stateId', 'choice', array(
                            'placeholder' => 'user.contact_book.stateId.select_value',
                            'empty_data'  => null,
                            'choices' => $state,
                    ));
                };

        $formModifier2 = function (FormInterface $form, $city) {
                    $form->add('cityId', 'choice', array(
                            'placeholder' => 'user.contact_book.cityId.select_value',
                            'empty_data'  => null,
                            'choices' => $city,
                    ));
                };

        $builder->addEventListener(
                        FormEvents::PRE_SET_DATA,
                        function (FormEvent $event) use ($formModifier1, $formModifier2, $master) {
                            // this would be your entity, i.e. SportMeetup
                            $data = $event->getData();
                            $country = $data->getCountryId()? $data->getCountryId():'233';
                            $state1 = $data->getStateId()? $data->getStateId():'';
                            $state=$master->getStateData($country);
                            $formModifier1($event->getForm(), $state);
                            $city=$master->getCityData($state1, $country);
                            $formModifier2($event->getForm(), $city);
                        }
                );



        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($formModifier1, $formModifier2, $master) {
                    $contactBook = $event->getData();
                    $form = $event->getForm();

                    if ($form->has('countryId')&& isset($contactBook['countryId'])) {
                        $stateDataArray=$master->getStateData($contactBook['countryId']);
                        $formModifier1($form, $stateDataArray);
                    }
                    if ($form->has('stateId') && isset($contactBook['stateId']) ) {
                        $cityDataArray=$master->getCityData($contactBook['stateId']);

                        $formModifier2($form, $cityDataArray);
                    }

                });
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'OfficeBrain\Bundle\UserBundle\Entity\ContactBook'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'ob_contactbook';
    }
}
