<?php

namespace OfficeBrain\Bundle\CategoryBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use OfficeBrain\Bundle\SolrBundle\Helper\ProductHelper;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Form\FormError;

/**
 * Sync product Category data command
 *
 * @author OfficeBrain 4220 <info@officebrain.com>
 */
class UpdateProductCategoryActiveOrInactiveSyncCommand extends ContainerAwareCommand
{
    CONST COMMAND_NAME = 'office_brain:solr:sync:product-category-active-inactive';
    
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName(self::COMMAND_NAME)
            ->setDescription('Command to sync category product data on active or inactive')
        	->addOption('instanceId', null, InputOption::VALUE_OPTIONAL, 'project instance Id')
        	->addOption('culture', null, InputOption::VALUE_OPTIONAL, 'supported search culture')
        	->addOption('categoryId', null, InputOption::VALUE_OPTIONAL, 'Valid Category id that is pms id of category. ')
        	->addOption('schedularId', null, InputOption::VALUE_OPTIONAL, 'schedularId. ')
        	->addOption('action', null, InputOption::VALUE_OPTIONAL, 'add/delete');
    }
    
    public function init() {
    	$this->container = $this->getContainer();
    	$this->request = $this->container->get('request');
    	$this->projectSetting = $this->request->get('project_setting');
    	$this->localeLanguage = $this->projectSetting['locale_language'];
    	$this->getCultureValue();
    	$this->entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
    	$this->apiManager = $this->container->get('officebrain_category_api_manager');
    	$this->searchManager = $this->container->get('office_brain_search_manager');
    	$this->formFactory = $this->container->get('form.factory');
    	$this->languageId = $this->getLanguageId();
    	$this->responseArray = array();
    	$this->productSearchClient = $this->container->get('office_brain_solr.product_search');
    	if(isset($this->projectSetting['instance_theme_meta']['product_category']['custom_label'])){
    		$this->categoryCustomlabel = $this->projectSetting['instance_theme_meta']['product_category']['custom_label'];
    	}
    	   	
    }
    

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
    	$this->init();
    	$startAt = microtime(true);
    	$categoryId= $input->getOption('categoryId','');
    	$instanceId= $input->getOption('instanceId',null);
    	$culture = $input->getOption('culture',null);
    	$action = $input->getOption('action',null);
    	$schedularId = $input->getOption('schedularId',null);
    	$categoryArray = array();
    	
    	

    	if ($categoryId == '') {
    		$output->writeln("Please provide a category id");
    		return;
    	}
    	
    	if ($instanceId == '') {
    		$output->writeln("Please provide a instance id");
    		return;
    	}
    	
    	if ($culture == '') {
    		$output->writeln("Please provide a culture");
    		return;
    	}
    	
    	if ($action == '') {
    		$output->writeln("Please provide a action");
    		return;
    	}

    	//$productCounts = 0;
		$searchQuery = $this->searchManager->getSearchArray();
		$searchQuery['product_search']['instanceId']= $instanceId;
		if($categoryId!=0 || $categoryId !='' ){
			if ($action == 'add') {
				$searchQuery['product_search']['inactiveCategoryId']= json_encode(array($categoryId.'|*'));
			}else{
				$searchQuery['product_search']['categoryId']= json_encode(array($categoryId));
			}
		}    		    			
		$productSearchData = new ProductSearchData($this->entityManager, $this->languageId);
		$productSearchForm = new ProductSearchType();
		$this->form = $this->formFactory->create($productSearchForm, $productSearchData, array('csrf_protection' => false));
		$this->form->bind($searchQuery['product_search']);
		$this->responseArray = $this->searchManager->searchResult($this->form->getData(),true);
		if(isset($this->responseArray['search_result_array']['data']) && count($this->responseArray['search_result_array']['data']) > 0)
		{
			$productData = $this->responseArray['search_result_array']['data'];
			if ($culture !== null) {
				$this->productSearchClient->setSearchCulture($culture);
			}
			$update = $this->productSearchClient->getCreateUpdateInstance();
			if($action == 'add'){
				$this->activeCategory($update,$productData,$culture,$categoryId);
			}else{
				$this->inactiveCategory($update,$productData,$culture,$categoryId);
			}
			
			$output->writeln('Completed For category '.$categoryId .' And Total Products : '. count($productData));
			if ($schedularId != '') {
				$callApi = $this->apiManager->getSchedularCategoryById($schedularId);
				if($callApi!=NULL){
					$pmsId = $callApi->getPmsId();
					$categoryStatus=$callApi->getCategoryStatus();
					$name=$callApi->getName();
					$id=$callApi->getId();
					$this->apiManager->addCategoryStatusSchedular($pmsId,$categoryStatus,$name,'Done',$id);
				}
			}
		}
		else
		{
			$output->writeln('No product found for category  '.$categoryId);
			if ($schedularId != '') {
				$callApi = $this->apiManager->getSchedularCategoryById($schedularId);
				if($callApi!=NULL){
					$pmsId = $callApi->getPmsId();
					$categoryStatus=$callApi->getCategoryStatus();
					$name=$callApi->getName();
					$id=$callApi->getId();
					$this->apiManager->addCategoryStatusSchedular($pmsId,$categoryStatus,$name,'Done',$id);
				}
			}
		}
    }
    
    public function activeCategory($update,$productData,$culture,$categoryId)
    {
		$this->init();
    	foreach ($productData as $product)
		{
			$doc = $update->createDocument ();
			echo $product['product_id'];
			$doc->setKey('id', $product['instance_id']."-".$product['product_id']);
			
			$categoryName = "";
			$categoryIdName="";

			if(isset($product ['inactive_category_id_ss'])){

				$result = $result = array_filter($product ['inactive_category_id_ss'], function ($value) use ($categoryId){
				return strpos($value, $categoryId.'|') === 0;
				});
				$result = array_values($result);
				$categoryIdName = $result[0];
				$categoryName = explode('|',$categoryIdName);
				$categoryName = $categoryName[1];

				$product ['inactive_category_id_ss'] = $this->sliceDataFromArray($product ['inactive_category_id_ss'], $categoryIdName);
				if(count($product ['inactive_category_id_ss'])==0){
					$product ['inactive_category_id_ss'][] = 0; 
				}
				$doc->setField('inactive_category_id_ss',$product ['inactive_category_id_ss']);
				$doc->setFieldModifier('inactive_category_id_ss', 'set');
			}
			
			if(isset($product ['category_is'])){
				$product ['category_is'] = $this->sliceDataFromArray($product ['category_is'], 0);
				if(!in_array($categoryId,$product['category_is'])){
					$product['category_is'][] = $categoryId;
					$doc->setField('category_is',$product ['category_is']);
					$doc->setFieldModifier('category_is', 'set');
				}
			}
			
			if(isset($product ['category_name_ss'])){
				$product ['category_name_ss'] = $this->sliceDataFromArray($product ['category_name_ss'], 0);
				if(!in_array($categoryName,$product['category_name_ss'])){
					$product['category_name_ss'][] = $categoryName;
					$doc->setField('category_name_ss',$product ['category_name_ss']);
					$doc->setFieldModifier('category_name_ss', 'set');
				}
			}
			
			if(isset($product ['category_name_txt'])){
				$product ['category_name_txt'] = $this->sliceDataFromArray($product ['category_name_txt'], 0);
				if(!in_array($categoryName,$product['category_name_txt'])){
					$product ['category_name_txt'][] = $categoryName;
					$doc->setField('category_name_txt',$product ['category_name_txt']);
					$doc->setFieldModifier('category_name_txt', 'set');
				}
			}
			
			if(isset($product ['category_name_id_ss'])){
				$product ['category_name_id_ss'] = $this->sliceDataFromArray($product ['category_name_id_ss'], 0);
				if(!in_array($categoryIdName,$product['category_name_id_ss'])){
					$product ['category_name_id_ss'][] = $categoryIdName;
					$doc->setField('category_name_id_ss',$product ['category_name_id_ss']);
					$doc->setFieldModifier('category_name_id_ss', 'set');
				}
			}
			
			
			$update->addDocument($doc);
			
			$update->addCommit();
			$this->clientFactoryService = $this->getContainer()->get('office_brain_solr.client_factory_service');
			$this->searchClient = $this->clientFactoryService->getProductSearchClientInstance ( $culture );
			$this->searchClient->update($update);

			/*\Doctrine\Common\Util\Debug::dump($doc);
			die("Herer");*/
		}
   
	}
	
	
    public function inactiveCategory($update,$productData,$culture,$categoryId)
    {
    	$this->init();
    	foreach ($productData as $product)
		{
			$doc = $update->createDocument ();
			echo $product['product_id'];
			$doc->setKey('id', $product['instance_id']."-".$product['product_id']);
			
			$categoryName = "";
			$categoryIdName="";
			if(isset($product ['category_name_id_ss'])){

				$result = $result = array_filter($product ['category_name_id_ss'], function ($value) use ($categoryId){
				return strpos($value, $categoryId.'|') === 0;
				});
				$result = array_values($result);
				$categoryIdName = $result[0];
				$categoryName = explode('|',$categoryIdName);
				$categoryName = $categoryName[1];
				//echo $categoryIdName; echo "\n";
				//echo $categoryName; die;

				$product ['category_name_id_ss'] = $this->sliceDataFromArray($product ['category_name_id_ss'], $categoryIdName);
				if(count($product ['category_name_id_ss'])==0){
					$product ['category_name_id_ss'][] = 0; 
				}
				$doc->setField('category_name_id_ss',$product ['category_name_id_ss']);
				$doc->setFieldModifier('category_name_id_ss', 'set');
			}

			if(isset($product ['inactive_category_id_ss'])){
				$product ['inactive_category_id_ss'] = $this->sliceDataFromArray($product ['inactive_category_id_ss'], 0);
				$cnt = count($product ['inactive_category_id_ss']);
				if($cnt>0){
					$product ['inactive_category_id_ss'][$cnt] = $categoryIdName;
					$doc->setField('inactive_category_id_ss', $product ['inactive_category_id_ss']);
					$doc->setFieldModifier('inactive_category_id_ss', 'set');
				}else{
					$doc->setField('inactive_category_id_ss', array($categoryIdName));
					$doc->setFieldModifier('inactive_category_id_ss', 'set');
				}
			}else{
			$doc->setField('inactive_category_id_ss', array($categoryIdName));
			$doc->setFieldModifier('inactive_category_id_ss', 'set');
			}
			
			if(isset($product ['category_is'])){
				$product ['category_is'] = $this->sliceDataFromArray($product ['category_is'], $categoryId);
				if(count($product ['category_is'])==0){
					$product ['category_is'][] = 0; 
				}
				$doc->setField('category_is',$product ['category_is']);
				$doc->setFieldModifier('category_is', 'set');
			}
			
			if(isset($product ['category_name_ss'])){
				$product ['category_name_ss'] = $this->sliceDataFromArray($product ['category_name_ss'], $categoryName);
				if(count($product ['category_name_ss'])==0){
					$product ['category_name_ss'][] = 0; 
				}
				$doc->setField('category_name_ss',$product ['category_name_ss']);
				$doc->setFieldModifier('category_name_ss', 'set');
			}
			
			if(isset($product ['category_name_txt'])){
				$product ['category_name_txt'] = $this->sliceDataFromArray($product ['category_name_txt'], $categoryName);
				if(count($product ['category_name_txt'])==0){
					$product ['category_name_txt'][] = 0; 
				}
				$doc->setField('category_name_txt',$product ['category_name_txt']);
				$doc->setFieldModifier('category_name_txt', 'set');
				
			}
			
			
			$update->addDocument($doc);
			
			$update->addCommit();
			$this->clientFactoryService = $this->getContainer()->get('office_brain_solr.client_factory_service');
			$this->searchClient = $this->clientFactoryService->getProductSearchClientInstance ( $culture );
			$this->searchClient->update($update);

			/*\Doctrine\Common\Util\Debug::dump($doc);
			die("Herer");*/
		}
    }
    
    private function sliceDataFromArray($array, $sliceData){
		$array = array_diff($array, array($sliceData));
		$array = array_values($array);
		return $array; 
	}
	
    public function getCultureValue()
    {
    	$cultures = array();
    
    	if ($this->localeLanguage && $this->localeLanguage != '' && (int) $this->localeLanguage == 0) {
    		list($this->languageCode, $this->countryCode) = explode('_', $this->localeLanguage);
    	}
    
    	return $cultures;
    }
    
    public function getLanguageId(){
	    switch ($this->languageCode) {
	    	case 'fr':
	    		$language = '3';
	    		break;
	    	default:
	    		$language = '1';
	    		break;
	    }	    
	    return $language;
    }
    
}
