<?php

namespace Lc\ShopBundle\Controller\Backend;

use App\Entity\Product;
use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
use Lc\ShopBundle\Context\OrderShopInterface;
use Lc\ShopBundle\Context\ProductCategoryInterface;
use Lc\ShopBundle\Context\ProductFamilyInterface;
use Lc\ShopBundle\Context\ReductionCatalogInterface;
use Lc\ShopBundle\Context\TaxRateInterface;
use Lc\ShopBundle\Form\Backend\Common\ReductionCatalogType;
use Lc\ShopBundle\Form\Backend\ProductFamily\ProductType;
use Lc\ShopBundle\Model\ProductFamily;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Response;

class ProductFamilyController extends AdminController
{
        private $taxRateClass;
        private $choicesTaxRateParam;
        private $choicesSupplierTaxRateParam;

        public function createEntityFormBuilder($entity, $view, $override = true)
        {

                $formBuilder = parent::createEntityFormBuilder($entity, $view, false);

                $class = $this->em->getClassMetadata(ProductCategoryInterface::class);
                $this->taxRateClass = $this->em->getClassMetadata(TaxRateInterface::class);

                //$formBuilder->add('productCategories', ProductFamilyCategoriesType::class);


                $reductionCatalogRepo = $this->em->getRepository(ReductionCatalogInterface::class);

                $reductionCatalogClass = $this->em->getClassMetadata(ReductionCatalogInterface::class);
                $reductionCatalog = $reductionCatalogRepo->findOneBy(array('status'=>false, 'productFamily'=>$entity));

                if($reductionCatalog == null)$reductionCatalog = new $reductionCatalogClass->name;
                $formBuilder->add('reductionCatalog', ReductionCatalogType::class,array(
                        'mapped'=>false,
                        'data'=> $reductionCatalog
                ));


                $formBuilder->add('warningMessageType', ChoiceType::class, array(
                        'choices' => array(
                                'field.default.warningMessageTypeOptions.'.ProductFamily::WARNING_MESSAGE_TYPE_SUCCESS => ProductFamily::WARNING_MESSAGE_TYPE_SUCCESS,
                                'field.default.warningMessageTypeOptions.'.ProductFamily::WARNING_MESSAGE_TYPE_ERROR => ProductFamily::WARNING_MESSAGE_TYPE_ERROR,
                                'field.default.warningMessageTypeOptions.'.ProductFamily::WARNING_MESSAGE_TYPE_WARNING => ProductFamily::WARNING_MESSAGE_TYPE_WARNING,
                                'field.default.warningMessageTypeOptions.'.ProductFamily::WARNING_MESSAGE_TYPE_INFO => ProductFamily::WARNING_MESSAGE_TYPE_INFO
                        ),
                        'translation_domain' => 'lcshop',
                        'multiple' => false,
                        'expanded' => false,
                        'required' => false
                ));

                $formBuilder->add('behaviorCountStock', ChoiceType::class, array(
                        'empty_data' => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY,
                        'choices' => array(
                                'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE,
                                'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY,
                                'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT,
                                'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_UNLIMITED => ProductFamily::BEHAVIOR_COUNT_STOCK_UNLIMITED
                        ),
                        'translation_domain' => 'lcshop',
                        'multiple' => false,
                        'expanded' => true
                ));

                $formBuilder->add('behaviorAddToCart', ChoiceType::class, array(
                        'data' => $entity->getBehaviorAddToCart() ? $entity->getBehaviorAddToCart() : 'simple',
                        'choices' => array(
                                'field.ProductFamily.behaviorAddToCartOptions.'.ProductFamily::BEHAVIOR_ADD_TO_CART_SIMPLE => ProductFamily::BEHAVIOR_ADD_TO_CART_SIMPLE,
                                'field.ProductFamily.behaviorAddToCartOptions.'.ProductFamily::BEHAVIOR_ADD_TO_CART_MULTIPLE => ProductFamily::BEHAVIOR_ADD_TO_CART_MULTIPLE
                        ),
                        'translation_domain' => 'lcshop',
                        'multiple' => false,
                        'expanded' => true
                ));

                $formBuilder->add('behaviorPrice', ChoiceType::class, array(
                        'empty_data' => 'by-piece',
                        'choices' => array(
                                'field.ProductFamily.behaviorPriceOptions.'.ProductFamily::BEHAVIOR_PRICE_BY_PIECE => ProductFamily::BEHAVIOR_PRICE_BY_PIECE,
                                'field.ProductFamily.behaviorPriceOptions.'.ProductFamily::BEHAVIOR_PRICE_BY_REFERENCE_UNIT => ProductFamily::BEHAVIOR_PRICE_BY_REFERENCE_UNIT
                        ),
                        'translation_domain' => 'lcshop',
                        'multiple' => false,
                        'expanded' => true
                ));

                $formBuilder->add('multiplyingFactor', NumberType::class, array(
                        'mapped'=> false,
                        'data'=> floatval($this->merchantUtils->getMerchantConfig('multiplying-factor')),
                ));

                $formBuilder->add('propertyOrganicLabel', ChoiceType::class, array(
                        'choices' => array(
                                'field.ProductFamily.organicLabelOptions.'.ProductFamily::PROPERTY_ORGANIC_LABEL_AB => ProductFamily::PROPERTY_ORGANIC_LABEL_AB,
                                'field.ProductFamily.organicLabelOptions.'.ProductFamily::PROPERTY_ORGANIC_LABEL_NP => ProductFamily::PROPERTY_ORGANIC_LABEL_NP,
                                'field.ProductFamily.organicLabelOptions.'.ProductFamily::PROPERTY_ORGANIC_LABEL_HVE => ProductFamily::PROPERTY_ORGANIC_LABEL_HVE
                        ),
                        'translation_domain' => 'lcshop',
                        'multiple' => false,
                        'expanded' => false,
                        'required' => false
                ));

                $formBuilder->add('typeExpirationDate', ChoiceType::class, array(
                        'choices' => array(
                                'field.default.'.ProductFamily::TYPE_EXPIRATION_DATE_DLC => ProductFamily::TYPE_EXPIRATION_DATE_DLC,
                                'field.default.'.ProductFamily::TYPE_EXPIRATION_DATE_DDM => ProductFamily::TYPE_EXPIRATION_DATE_DDM,
                                'field.default.'.ProductFamily::TYPE_EXPIRATION_DATE_DLUO => ProductFamily::TYPE_EXPIRATION_DATE_DLUO
                        ),
                        'translation_domain' => 'lcshop',
                        'multiple' => false,
                        'expanded' => true,
                        'required'=>false
                ));

                $formBuilder->add('behaviorStockWeek', ChoiceType::class, array(
                        'choices' => array(
                                'field.ProductFamily.behaviorStockWeekOptions.'.ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE => ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE,
                                'field.ProductFamily.behaviorStockWeekOptions.'.ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE_VALIDATION => ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE_VALIDATION,
                                'field.ProductFamily.behaviorStockWeekOptions.'.ProductFamily::BEHAVIOR_STOCK_WEEK_NON_RENEWABLE => ProductFamily::BEHAVIOR_STOCK_WEEK_NON_RENEWABLE
                        ),
                        'translation_domain' => 'lcshop',
                        'multiple' => false,
                        'expanded' => true,
                        'required'=>true
                ));

                $formBuilder->add('behaviorExpirationDate', ChoiceType::class, array(
                        'choices' => array(
                                'field.ProductFamily.behaviorExpirationDateOptions.'.ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT_FAMILY => ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT_FAMILY,
                                'field.ProductFamily.behaviorExpirationDateOptions.'.ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT => ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT
                        ),
                        'translation_domain' => 'lcshop',
                        'multiple' => false,
                        'expanded' => true,
                        'required'=>false
                ));


                $formBuilder->add('products', CollectionType::class, array(
                                'label' => 'Déclinaisons',
                                'entry_type' => ProductType::class,
                                'entry_options' => ['label' => false],
                                'allow_add' => true,
                                'allow_delete' => true,
                                'required' => true
                        )
                );

                $formBuilder = $this->overrideFormBuilder($formBuilder, $entity, $view);

                return $formBuilder;
        }

        public function updateProductFamilyEntity($entity, $editForm)
        {
                $this->processReductionCatalog($entity, $editForm);
                $this->processCategories($entity);
                $this->processProducts($entity);
                $this->processPrice($entity);

                parent::updateEntity($entity);
        }

        public function persistProductFamilyEntity($entity, $newForm)
        {
                $this->processReductionCatalog($entity, $newForm);
                $this->processCategories($entity);
                $this->processProducts($entity);
                $this->processPrice($entity);

                $this->em->persist($entity);
                $this->em->flush();
        }

        protected function processReductionCatalog($entity, $editForm){
                $reductionCatalog = $editForm->get('reductionCatalog')->getData();
                if($reductionCatalog instanceof ReductionCatalogInterface ) {
                        if($reductionCatalog->getValue() && $reductionCatalog->getBehaviorTaxRate() && $reductionCatalog->getUnit()){
                                $reductionCatalog->setMerchant($entity->getMerchant());
                                $reductionCatalog->setStatus($editForm->get('activeReductionCatalog')->getData());
                                $reductionCatalog->setProductFamily($entity);
                                $this->em->persist($reductionCatalog);
                        }
                }
        }

        protected function processPrice($entity){
                if($entity->getBehaviorPrice()=='by-piece'){
                        $entity->setPriceByRefUnit(null);
                        $entity->setBuyingPriceByRefUnit(null);
                }else if($entity->getBehaviorPrice()=='by-reference-unit') {
                        $entity->setPrice(null);
                        $entity->setBuyingPrice(null);
                }
        }

        protected function processProducts($entity)
        {
                //si il existe un et un seul produit pour ce product family n'ajoute rien supprime rien
                if (count($entity->getProducts()) == 0) {
                        $product = new Product();
                        $product->setProductFamily($entity);
                        $this->em->persist($product);
                        $entity->addProduct($product);
                } else {
                        foreach ($entity->getProducts() as $i=>$product) {
                                $product->setProductFamily($entity);
                                $this->em->persist($product);
                                $entity->addProduct($product);
                        }
                }

        }

        protected function processCategories(ProductFamilyInterface $entity)
        {
                $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
                $productCategories = $entity->getProductCategories();

                $entity->initProductCategories();

                foreach ($productCategories as $key => $bool) {
                        if (is_bool($bool) && $bool) {
                                if (strpos($key, 'category_children_') !== false) {
                                        $idCategory = (int)str_replace('category_children_', '', $key);
                                } else {
                                        $idCategory = (int)str_replace('category_', '', $key);
                                }

                                $category = $productCategoryRepository->find($idCategory);
                                $entity->addProductCategory($category);
                        }
                }
        }

        protected function editAction()
        {

                $this->dispatch(EasyAdminEvents::PRE_EDIT);

                $id = $this->request->query->get('id');
                $easyadmin = $this->request->attributes->get('easyadmin');
                $entity = $easyadmin['item'];




                $orderShopRepo = $this->em->getRepository(OrderShopInterface::class);

                $totalProductOrdered = array();
                foreach ($entity->getProducts() as $product) {
                        $currentWeekNumber = $this->orderUtils->getWeekNumberCurrent();
                        //Les commandes sont ouvertes ont récupèrent les commandes en cours et celle de la semaine dernière
                        if($this->orderUtils->isOpenSale()) {
                                $totalProductOrdered[$product->getId()][$currentWeekNumber] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber, $product->getId());
                                $totalProductOrdered[$product->getId()][$currentWeekNumber - 1] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber - 1, $product->getId());
                        }else{
                                $totalProductOrdered[$product->getId()][$currentWeekNumber] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber, $product->getId());
                        }
                }



                if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
                        $newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
                        $fieldsMetadata = $this->entity['list']['fields'];

                        if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
                                throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
                        }

                        $this->updateEntityProperty($entity, $property, $newValue);

                        // cast to integer instead of string to avoid sending empty responses for 'false'
                        return new Response((int)$newValue);
                }

                $fields = $this->entity['edit']['fields'];

                $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
                $deleteForm = $this->createDeleteForm($this->entity['name'], $id);

                $sortableProductsField = array();
                foreach ($editForm->get('products')->getData() as $k => $product) {
                        $sortableProductsField[$product->getPosition()] = $k;
                }
                ksort($sortableProductsField);

                $editForm->handleRequest($this->request);

                if( $editForm->isSubmitted() && count($entity->getProductCategories()) == 0){
                        $editForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
                }

                if ($editForm->isSubmitted() && $editForm->isValid() && count($entity->getProductCategories())>0) {

                        $this->processUploadedFiles($editForm);

                        $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
                        $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
                        $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);

                        return $this->redirectToReferrer();
                }

                $this->dispatch(EasyAdminEvents::POST_EDIT);

                $parameters = [
                        'form' => $editForm->createView(),
                        'entity_fields' => $fields,
                        'entity' => $entity,
                        'delete_form' => $deleteForm->createView(),
                        'sortableProductsField' => $sortableProductsField,
                        'totalProductOrdered' => $totalProductOrdered
                ];

                return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
        }

        protected function newAction()
        {
                $this->dispatch(EasyAdminEvents::PRE_NEW);

                $entity = $this->executeDynamicMethod('createNew<EntityName>Entity');

                $easyadmin = $this->request->attributes->get('easyadmin');
                $easyadmin['item'] = $entity;
                $this->request->attributes->set('easyadmin', $easyadmin);

                $fields = $this->entity['new']['fields'];

                $newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);

                $newForm->handleRequest($this->request);


                if( $newForm->isSubmitted() && array_search(true, $newForm->get('productCategories')->getData()->toArray())===false){
                        $newForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
                }

                if ($newForm->isSubmitted() && $newForm->isValid() && array_search(true, $newForm->get('productCategories')->getData()->toArray())!==false) {
                        $this->processUploadedFiles($newForm);

                        $this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
                        $this->executeDynamicMethod('persist<EntityName>Entity', [$entity, $newForm]);
                        $this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);

                        return $this->redirectToReferrer();
                }

                $this->dispatch(EasyAdminEvents::POST_NEW, [
                        'entity_fields' => $fields,
                        'form' => $newForm,
                        'entity' => $entity
                ]);

                $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
                $categories = $productCategoryRepository->findAllParents();

                $parameters = [
                        'form' => $newForm->createView(),
                        'entity_fields' => $fields,
                        'entity' => $entity,
                        'categories' => $categories,
                        'sortableProductsField' => array(),
                        'totalProductOrdered' => array()
                ];

                return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
        }

}