<?php

namespace OfficeBrain\Bundle\ServiceGroupBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\ExecutionContextInterface;
use Symfony\Component\Validator\Constraints as Assert;

class ServiceChargesRuleMappingType extends AbstractType
{
    /**
     * @param ContainerInterface $container
     */
    /*
     * public function __construct(ContainerInterface $container) { $this->container = $container; }
    */
    private $controllerObj = null;
    private $options = null;
    private $serviceRuleManager = null;
    protected $startDate = null;
    protected $endDate = null;

    public function __construct(ContainerInterface $container, array $fromAdmin = array())
    {
        $this->container = $container;

        $this->serviceGroupRuleOptions = $this->container->get('office_brain_service_group_rule_manager');
        $this->options['charge_operators'] = $this->serviceGroupRuleOptions->getActionChargesOperators();
        // set false when admin submitted updated registration form.
        $this->formMode = (isset($fromAdmin ['mode'])) ? $fromAdmin ['mode'] : 'add';

        if (isset($fromAdmin ['culture']) && $fromAdmin ['culture'] != null) {
            $this->options['culture'] = $fromAdmin ['culture'];
        } else {
            $this->options['culture'] = array();
        }

        if (isset($fromAdmin ['amount_type']) && $fromAdmin ['amount_type'] != null) {
            $this->options['amount_type'] = $fromAdmin ['amount_type'];
        } else {
            $this->options['amount_type'] = array();
        }

        if (isset($fromAdmin ['charge_type']) && $fromAdmin ['charge_type'] != null) {
            $this->options['charge_type'] = $fromAdmin ['charge_type'];
        } else {
            $this->options['charge_type'] = array();
        }

        if (isset($fromAdmin ['rule_status']) && $fromAdmin ['rule_status'] != null) {
            $this->options['rule_status'] = $fromAdmin ['rule_status'];
        } else {
            $this->options['rule_status'] = array();
        }
    }
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id', 'hidden', array('required' => false))
            ->add('serviceRuleMappingGroupId', 'entity',
                    array(
                            'class' => 'OfficeBrainServiceGroupBundle:ServiceGroupLanguage',
                            /*'query_builder' => function(\OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceGroupLanguageRepository $er) {
                                $qb = $er->createQueryBuilder('sgl')
                                            ->leftJoin('OfficeBrainServiceGroupBundle:ServiceGroup', 'sg', 'WITH', 'sg.id = sgl.serviceGroup')
                                            ->where('sgl.languageId=:languageId')
                                            ->andWhere('sg.countryId=:countryId')
                                            ->setParameter('countryId',2)
                                            ->setParameter('languageId',1);
                                return $qb;
                            },*/

                            'choice_label' => 'groupName',
                            'choice_value' => 'id',
                            /*'choice_attr' => array(
        						//'serviceGroup.id' => array('data-class' => 'text-muted'),
        					),*/
                            'multiple' => true,
                            'required' => true,
                            'mapped' => false,
                            'constraints' => array(new NotBlank(array('message' => 'admin.charges_rule_mapping.service_group.not_blank'))),
                    )
            )
        ;

        //$builder->add('serviceRuleMappingGroupId', 'choice', array('type' => new ServiceRuleMappingGroupType(), 'cascade_validation' => true));

        $builder
            ->add('startDate', 'date',
                array('required' => false,
                        'widget' => 'single_text',
                        'html5' => false,
                        'read_only' => true,
                        'format' => 'MM-dd-yyyy',
                        'constraints' => array(
                                new Assert\Callback(array('methods' => array(array($this, 'checkStartDate')))),
                                //new Assert\Callback(array('methods'=>array(array($this,'checkStartDateIsMin'))))
                        ),
                )
        )
        ->add('endDate', 'date',
                array('required' => false,
                        'widget' => 'single_text',
                        'html5' => false,
                        'read_only' => true,
                        'format' => 'MM-dd-yyyy',
                        'constraints' => array(
                                new Assert\Callback(array('methods' => array(array($this, 'checkEndDate')))),
                                new Assert\Callback(array('methods' => array(array($this, 'checkEndDateIsMax')))),

                        ),
                )
        )
        ->add('chargesType', 'choice',
                array('required' => false,
                        'choices' => $this->options['charge_type'],
                        'constraints' => array(
                                new NotBlank(array('message' => 'admin.charges_rule_mapping.charges_type.not_blank')),
                                new Assert\Callback(array('methods' => array(array($this, 'checkchargeType')))),
                        )
                )
        )
        ->add('serviceRuleChargesEquationId', 'collection', array(
                    'type' => new ServiceRuleChargesEquationType($this->options),
                    'allow_add' => true,
                    'allow_delete' => true,
                    'by_reference' => false,
                    //'prototype_name' => "email",
                    'delete_empty' => true,
                    'options' => array(
                            'label' => false
                        )
                ))

        ->add('priority', 'text',
                array('required' => true,
                        'constraints' => array(
                                new NotBlank(array('message' => 'admin.charges_rule_mapping.priority.not_blank')),
                                new Assert\Callback(array('methods' => array(array($this, 'checkValidDecimal')))),
                                                        new Assert\Callback(array('methods' => array(array($this, 'checkvalidPriority')))),

                        ), )
        )
        ;

        $builder->add('status', 'choice', array(
            'required' => false,
            'multiple' => false,
            'choices' => $this->options['rule_status'],
        ));

        if ($this->formMode == 'add') {
            $builder->add('countryId', 'choice', array(
                    'empty_value' => false,
                    'label' => 'Country',
                    'choices' => $this->options['culture'],
                    'data' => 1,
                    'required' => true,
                    'constraints' => array(new NotBlank(array('message' => 'admin.charges_rule_mapping.country.not_blank.'))),
                    'expanded' => true,
            ));
        } else {
            $builder->add('countryId', 'choice', array(
                    'label' => 'Country',
                    'choices' => $this->options['culture'],
                    'required' => false,
                    'read_only' => true,
                    'empty_value' => false,
                    'multiple' => false,
                    'expanded' => true,
            ));
        }
    }

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

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

    public function setForm($form)
    {
        $this->form = $form;
    }

    public function setControllerObj($obj)
    {
        $this->ControllerObj = $obj;
    }

    public function setServiceRuleManager($serviceRuleManager)
    {
        $this->serviceRuleManager = $serviceRuleManager;
    }

    public function setRequest($request)
    {
        $this->request = $request;
    }
    public function checkchargeType($data, ExecutionContextInterface $context)
    {
        $this->chargeType = $data;
    }
    public function checkvalidPriority($data, ExecutionContextInterface $context)
    {
        if ($this->serviceRuleManager) {
            $countryId = $this->form->get('countryId')->getData();
            $id = $this->form->get('id')->getData();

            if ($this->serviceRuleManager->checkvalidPriority($countryId, $data, $id) > 0) {
                $context->addViolation('admin.charges_rule_mapping.priority.exists');
            }
        }
    }
    public function checkStartDate($data, ExecutionContextInterface $context)
    {
        if (!$this->checkMyDate($data)) {
            $context->addViolation('admin.charges_rule_mapping.start_date.valid');
        }
        $this->startDate = $data;
    }
    public function checkEndDate($data, ExecutionContextInterface $context)
    {
        if (!$this->checkMyDate($data)) {
            $context->addViolation('admin.charges_rule_mapping.end_date.valid');
        }
        $this->endDate = $data;
    }

    public function checkEndDateIsMax($data, ExecutionContextInterface $context)
    {
        if ($this->startDate && $this->endDate) {
            if ($this->startDate > $this->endDate) {
                $context->addViolation('admin.charges_rule_mapping.end_date.greater_start_date');
            }
        }
    }

    public function checkStartDateIsMin($startDate, ExecutionContextInterface $context)
    {
        $oldDate = $this->request->get('old_start_date', '');
        if (($oldDate != '' && $oldDate != $startDate) && $startDate < date('Y-m-d')) {
            $context->addViolation('admin.charges_rule_mapping.start_date.less_current_date');
        } elseif ($oldDate == '' && $startDate != null && $startDate < date('Y-m-d')) {
            $context->addViolation('admin.charges_rule_mapping.start_date.less_current_date');
        }
    }

    public function checkMyDate($date)
    {
        if ($date && $date != null) {
            return (checkdate($date->format('m'), $date->format('d'), $date->format('Y')));
        }

        return true;
    }
    public function checkRuleHasError($hasRuleCondError)
    {
        if ($hasRuleCondError) {
            $context->addViolation('admin.charges_rule_mapping.rules.unknow_error');
        }
    }


    public function checkamountType($data, ExecutionContextInterface $context)
    {
        $this->amountType = $data;
    }
    public function checkValidamountType($data, ExecutionContextInterface $context)
    {
        if ($this->amountType == '1' && $this->chargeType == '1') {
            $context->addViolation('admin.charges_rule_mapping.amount_type.valid');
        }
    }


    public function checkValidDecimal($data, ExecutionContextInterface $context)
    {
        if ($data != '' && !is_float($data) && !is_numeric($data)) {
            $context->addViolation('admin.charges_rule_mapping.amount.valid');
        }
    }
}
