<?php

namespace OfficeBrain\Bundle\SubShopBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
use Doctrine\ORM\Query\ResultSetMapping;
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;

/**
 * Sync Subshop Product From Product Criteria Command
 *
 * @author OfficeBrain 4494 <info@officebrain.com>
 */
class SyncSubShopProductCommand extends ContainerAwareCommand
{
    CONST COMMAND_NAME = 'office_brain:solr:sync:subshop-product';

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName(self::COMMAND_NAME)
            ->setDescription('Command to sync subshop product data')
            ->setDefinition(array(
                new InputOption('projectId', null, InputOption::VALUE_REQUIRED, 'project Id'),
                new InputOption('culture', '', InputOption::VALUE_REQUIRED, 'Supported search culture.'),
                new InputOption('instanceId', null, InputOption::VALUE_REQUIRED, 'Enter instance id for instance wise product Id'),
            	new InputOption('subShopInstanceId', null, InputOption::VALUE_REQUIRED, 'subshop instance Id'),
            	new InputOption('languageId', null, InputOption::VALUE_REQUIRED, 'language Id'),
            	new InputOption('productId', null, InputOption::VALUE_REQUIRED, 'product Id'),
            ))
            ->setHelp(<<<EOT
The <info>office_brain:solr:sync:subshop-product</info> command helps you to sync subshop products into solar schema.
EOT
            );
    }
    

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
    	$productIds = array();
        $startAt = microtime(true);
        
        $projectId = $input->getOption('projectId', null);
        $culture = $input->getOption('culture', null);
        $instanceId = $input->getOption('instanceId', null);
		$subShopInstanceId = $input->getOption('subShopInstanceId', null);
        $languageId = $input->getOption('languageId', null);
        $productId = $input->getOption('productId', null);
        
        $GLOBALS['instanceId'] = $instanceId;
        
        
        $event = new GetResponseEvent($this->getContainer()->get('kernel'),  $this->getContainer()->get('request'), HttpKernelInterface::MASTER_REQUEST);
        $accessListener = $this->getContainer()->get('office_brain_access_management.access_configuration');
        $accessListener->PrepareAccessAndConfigurationRulesForException ($event );
        
        $this->subShopThemeManager = $this->getContainer()->get('office_brain_subshop_theme_manager');
        $this->searchManager = $this->getContainer()->get('office_brain_search_manager');
        $this->entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
        $this->formManager = $this->getContainer()->get('form.factory');
        
        if ($projectId == '')
        {
        	$output->writeln("Please provide a project id !");
        	return;
        }

        if ($culture == null) {
        	$output->writeln("Please provide a culture !");
        	return;
        }
        
        if ($instanceId == '')
        {
        	$output->writeln("Please provide a instance id !");
        	return;
        }
        
        if ($subShopInstanceId == '')
        {
        	$output->writeln("Please provide a subshop instance id !");
        	return;
        }
        
        if ($languageId == '')
        {
        	$output->writeln("Please provide a language id !");
        	return;
        }

        $subShopInstanceMeta = $this->subShopThemeManager->getSubShopInstanceKey('product_criteria', $subShopInstanceId);
        $environment = $this->getContainer()->getParameter("kernel.environment");

        if (count($subShopInstanceMeta) > 0) {

        	if(empty($productId)){
	        	$kernelRootDir = 'php '.$this->subShopThemeManager->subShopMediaUploadLocation['kernel_root_dir'];
	        	$cmd = $kernelRootDir.DIRECTORY_SEPARATOR.'console office_brain:solr:sync:delete-product --instanceId='.$subShopInstanceId.' --projectId='.$projectId .' --culture='.$culture.' --env="'.$environment.'"';
	        	shell_exec($cmd);
        	}

        	$subShopInstanceMeta = json_decode($subShopInstanceMeta->getMetaValue(), 'Array');
        	$productSearchData = new ProductSearchData($this->entityManager, $languageId);
        
        	foreach ($subShopInstanceMeta as $country => $searchCriteria) {
        		$searchQuery = $this->getSearchQuery($searchCriteria);
        		$searchQuery['product_search']['instanceId'] = $instanceId;
        		if(!empty($productId)){
        			$searchQuery['product_search']['productId'] = $productId;
        		}
        		
        		$form = $this->formManager->create(new ProductSearchType(), $productSearchData, array('csrf_protection' => false));
        		//continue;
        		$form->bind($searchQuery['product_search']);
        		if ($form->isValid()) {
        			$searchProducts = $this->searchManager->searchResult($form->getData(), true);
					foreach ($searchProducts['search_result_array']['data'] as $val) {
						/* Add Data Local Product Master From Solr*/
						$distributorProductService = $this->getContainer()->get("officebrain_distributor_admin_manager");
						$distributorProductObj = $distributorProductService->existsDistributorProduct($val['product_id']);
						if(!is_object($distributorProductObj)){
							$localProductData = $distributorProductService->addFromSolr($val,$culture,$languageId);
						}
						/*EO Add Data Local Product Master From Solr*/
						if (!in_array($val['product_id'], $productIds))
        				{
        					$productIds[] = $val['product_id'];
        					$kernelRootDir = 'php '.$this->subShopThemeManager->subShopMediaUploadLocation['kernel_root_dir'];
        					$cmd = $kernelRootDir.DIRECTORY_SEPARATOR.'console office_brain:solr:sync:product --productId='.$val['product_id'].' --instanceId='.$subShopInstanceId.' --projectId='.$projectId .' --culture='.$culture.' --env="'.$environment.'"';
        					shell_exec($cmd);

        					unset($kernelRootDir);
        					unset($cmd);
        				}
        			}
        			$this->subShopThemeManager->setSubShopInstanceKey('product_solr_status', true, $subShopInstanceId);
        		}elseif(!empty($productId)){
		        	$kernelRootDir = 'php '.$this->subShopThemeManager->subShopMediaUploadLocation['kernel_root_dir'];
		        	$cmd = $kernelRootDir.DIRECTORY_SEPARATOR.'console office_brain:solr:sync:delete-product --productId='.$productId.' --instanceId='.$subShopInstanceId.' --projectId='.$projectId .' --culture='.$culture.'  --env="'.$environment.'"';
		        	shell_exec($cmd);
	        	}
        	}
        } else {
        	$output->writeln("Please provide a product criteria for given subshop instance id !");
        	return;
        }

        unset($projectId);
        unset($culture);
        unset($instanceId);
        unset($subShopInstanceId);
        unset($languageId);
        unset($this->subShopThemeManager);
        unset($this->searchManager);
        unset($this->entityManager);
        unset($this->formManager);
        unset($subShopInstanceMeta);
        unset($searchQuery);
        unset($form);
        unset($searchProducts);

        $output->writeln("Synchronous Product Id: " . implode(',', $productIds));
        $time_taken = microtime(true) - $startAt;
        $output->writeln("Processing time: " . sprintf("%.4f", ($time_taken)) . " seconds");
        $output->writeln("Memory Usage - " . number_format((memory_get_peak_usage() / 1048576),2) . " MB");

    }
    
    protected function getSearchQuery($params)
    {
    	$this->searchRequestArray = array();
    	
    	if (isset($params['search_query'])) {
    		$this->searchRequestArray['product_search']['keyword'] = trim($params['search_query']);
    	}
    	if (isset($params['min_price'])) {
    		$this->searchRequestArray['product_search']['min_price'] = trim($params['min_price']);
    	}
    
    	if (isset($params['max_price'])) {
    		$this->searchRequestArray['product_search']['max_price'] = trim($params['max_price']);
    	}
    
    	if (isset($params['category_filter'])) {
    		$this->searchRequestArray['product_search']['categoryId'] = $params['category_filter'];
    	}
    
    	if (isset($params['brand_filter'])) {
    		$this->searchRequestArray['product_search']['brandId'] = $params['brand_filter'];
    	}
    
    	if (isset($params['supplier_filter'])) {
    		$this->searchRequestArray['product_search']['supplierId'] =  $params['supplier_filter'];
    	}
    
    	if (isset($params['currency_filter'])) {
    		$this->searchRequestArray['product_search']['priceCurrency'] = $params['currency_filter'];
    	}
    
    	if (isset($params['rating_filter'])) {
    		$this->searchRequestArray['product_search']['rating'] = $params['rating_filter'];
    	}
    
    	if (isset($params['price_valid_until'])) {
    		$this->searchRequestArray['product_search']['priceValidUntil'] = $params['price_valid_until'];
    	}
    
    	if (isset($params['line_name_id'])) {
    		$this->searchRequestArray['product_search']['lineNameId'] = $params['line_name_id'];
    	}
    
    	if (isset($params['catalogyear_filter'])) {
    		$this->searchRequestArray['product_search']['catalogYear'] = $params['catalogyear_filter'];
    	}
    
    	if (isset($params['tag_filter'])) {
    		$this->searchRequestArray['product_search']['tag'] = trim($params['tag_filter']);
    	}
    
    	if (isset($params['attribute_filter'])) {
    		$this->searchRequestArray['product_search']['attribute'] = trim($params['attribute_filter']);
    	}
    
    	if (isset($params['colormapping_filter'])) {
    		$this->searchRequestArray['product_search']['colorMapping'] = trim($params['colormapping_filter']);
    	}
    
    	if (isset($params['save_search_name'])) {
    		$this->searchRequestArray['search']['save_search_name'] = trim($params['save_search_name']);
    	}
    
    	if (isset($params['sku'])) {
    		$this->searchRequestArray['product_search']['sku'] = trim($params['sku']);
    	}
    
    	if (isset($params['supplier_name'])) {
    		$this->searchRequestArray['product_search']['supplierName'] = $params['supplier_name'];
    	}
    
		return $this->searchRequestArray;
    }
}