<?php

namespace OfficeBrain\Bundle\CompanyBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Validator\ExecutionContextInterface as context;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\CssSelector\XPath\Translator;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Scandio\PlaygroundBundle\Validator as ScandioAssert;

class CompanyType extends AbstractType
{
    private $section;
    private $parent;
    public function __construct(ContainerInterface $container, $section, $userId='')
    {
        $this->container=$container;
        $this->section=$section;
        $this->userId=$userId;        
    }
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $master = $this->container->get('office_brain_core_manager');

        $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();
        }

        //$parentCompany=$companyMaster->getParentCompany();

        $builder
            ->add('companyName', 'text')
            ->add('companyAsiNumber', 'text')
            ->add('companyNumber', 'text')
            ->add('email', 'text')
            ->add('companyLogo', 'file', array('data_class' => null))            
            ->add('street1', 'text')
            ->add('street2', 'text');
        if ($this->section !='company') {
            if ($this->userId) {
                $builder->add('parent', 'entity', array(
                    'class' => 'OfficeBrainCompanyBundle:Company',
                    'query_builder' => function (EntityRepository $er) {
                                    return $er->createQueryBuilder('c')
                                    ->Where("c.companyName!=''")
                                    ->andWhere("c.parent is NULL")
                                    ->andWhere("c.createdUid =:userId")->setParameter('userId',$this->userId)
                                    ->andWhere("c.deletedAt is NULL")
                                    ->andWhere("c.status = 1")
                                    ->groupBy("c.companyName")
                                    ->orderBy('c.companyName', 'ASC');
                                },
                    'property' => 'companyName',
                    'placeholder' => 'select Company',
                    'empty_data'  => '',      
                    'constraints' => array(new Assert\NotBlank(array('message' => 'admin.company.parent.not_blank'))),
                ));   
            } else {
                $builder->add('parent', 'entity', array(
                    'class' => 'OfficeBrainCompanyBundle:Company',
                    'query_builder' => function (EntityRepository $er) {
                                    return $er->createQueryBuilder('c')
                                    ->Where("c.companyName!=''")
                                    ->andWhere("c.parent is NULL")
                                    ->andWhere("c.deletedAt is NULL")
                                    ->andWhere("c.status = 1")
                                    ->groupBy("c.companyName")
                                    ->orderBy('c.companyName', 'ASC');
                                },
                    'property' => 'companyName',
                    'placeholder' => 'select Company',
                    'empty_data'  => '',      
                    'constraints' => array(new Assert\NotBlank(array('message' => 'admin.company.parent.not_blank'))),
                ));
            }
        }
        $builder->add('countryId', 'choice', array(
                    'required' => true,
                    'empty_value' => 'Select country',
                    'choices' => $country
            ))
            ->add('stateId', 'choice', array(
                    'required' => true,
                    'empty_value' => "Select state",
                    'choices' => $state
            ))
            ->add('cityId', 'choice', array(
                    'required' => true,
                    'empty_value' => "Select city",
                    'choices' => $city
            ))
            ->add('zipcode', 'text')
            ->add('extension', 'text')
            ->add('phone', 'text')
            ->add('mobile', 'text')
            ->add('fax', 'text')
            ->add('website', 'text')
            ->add('erpId', 'hidden')
            ->add('status', 'hidden')
            ->add('companyLogoUrl','hidden');

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

        $formModifier2 = function (FormInterface $form, $city) {
                $form->add('cityId', 'choice', array(
                        'placeholder' => 'admin.company.cityId.select_value',
                        '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():'';
                        $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) {
                $user = $event->getData();
                $form = $event->getForm();

                $stateDataArray=$master->getStateData($user['countryId']);
                $formModifier1($form, $stateDataArray);

                $cityDataArray=$master->getCityData($user['stateId']);
                $formModifier2($form, $cityDataArray);

            });
    }

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

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