<?php

namespace OfficeBrain\Bundle\SolrBundle\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 Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;

/**
 * Sync product Category data command
 *
 * @author OfficeBrain 4220 <info@officebrain.com>
 */
class SyncProductWithExpiredSpecialPriceCommand extends ContainerAwareCommand
{
    CONST COMMAND_NAME = 'office_brain:solr:sync:productwithexpiredspecialprice';
    CONST TUBE_PREFIX = 'product_';
    CONST PAGING_LIMIT = 10;
    CONST PRODUCT_CACHE_CLIENT = 'product';
    
    protected $isOnlyCache;
    protected $categoryName;
    protected $languageId;
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName(self::COMMAND_NAME)
            ->setDescription('Command to sync product data')
            ->addOption('projectId', null, InputOption::VALUE_REQUIRED, 'project Id')
            ->addOption('instanceId', null, InputOption::VALUE_OPTIONAL, 'project instance Id')
            ->addOption('culture', null, InputOption::VALUE_OPTIONAL, 'supported search culture')
            ->addOption('productId', null, InputOption::VALUE_OPTIONAL, 'Product id')
            ->addOption('offset', null, InputOption::VALUE_OPTIONAL, 'offset for command operation')
            ->addOption('supplierId', null, InputOption::VALUE_OPTIONAL, 'Valid supplier id if value all is given than will execute for all active supplier\'s ')
            ->addOption('refSupplierId', null, InputOption::VALUE_OPTIONAL, 'Valid ref supplier id if value all is given than will execute for all active supplier\'s ')
            ->addOption('distributorId', null, InputOption::VALUE_OPTIONAL, 'Valid distributor id if value all is given than will execute for all active distributor\'s ')
            ->addOption('isOnlyCache', null, InputOption::VALUE_OPTIONAL, 'Enter 1 as value which you want to add only redis cache of product.');
    }
    
    public function init() {
    	$this->entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
    	$this->init();
    	
    	$solrConfig = $this->getContainer()->getParameter('solr');
    	$appConsolePath= $this->getContainer()->getParameter('app_console_path');
    	$phpPath= $this->getContainer()->getParameter('php_path');
    	$projectId = $this->getContainer()->getParameter('project_id');
    	$this->projectSetting = $this->getContainer()->get('request')->get('project_setting');
    	$this->instanceId = $this->projectSetting['instance_id'];
    	
    	$todaysDate = date("Y-m-d\TH:i:s\Z");
    	
    	$portString = '';
    	if(isset($solrConfig['port']) && $solrConfig['port'] != '')
    	{
    		$portString = ':'.$solrConfig['port'];
    	}
    	
    	$solrURL = 'http://'.$solrConfig['host'].$portString.'/solr/'.$solrConfig['core'].'/select?';
    	$solrQueryString = 'q=*:*&fq=price_valid_until_s:+[*+TO+'.$todaysDate.']&rows=1000&fl=product_id_i,price_valid_until_s,valid_up_to_dt&wt=csv&indent=true';
    	    	
    	$solrCompleteURL = $solrURL . $solrQueryString;
    	
    	$solrResponse = file_get_contents($solrCompleteURL);
    	
    	$output->writeln("\n========================================\n");
    	$output->writeln("\nExecuted Following Solr URL\n");
    	$output->writeln($solrCompleteURL);
    	
    	if($solrResponse!= '')
    	{
    		$output->writeln("\n========================================\n");
    		$output->writeln("\nSolr Response\n");
    		$output->writeln($solrResponse);
    		
    		// Remove Titles
    		$solrResponseArray = explode("\n",$solrResponse);
    		if(isset($solrResponseArray[0]))
    		{
    			if(!(is_int($solrResponseArray[0])))
    			{
    				unset($solrResponseArray[0]);
    			}
    		}
    		$solrCommands = '';
    		// Now process each Products If not blank
    		foreach($solrResponseArray as $i => $value)
    		{
    			if($value != '')
    			{ 
    				$valueArray = explode(",",$value);
    				$productId = $valueArray[0];
    				
    				$solrCommand = '';
    				// update product in all solr core defined in localization_to_fetch config
    				$localizationArray = $this->getContainer()->getParameter('localization_to_fetch');
    				if ($localizationArray && !empty($localizationArray)) {
    					foreach ($localizationArray as $localization) {
    						$solrCommand = "nohup ".$phpPath." ".$appConsolePath."/console office_brain:solr:sync:product --culture=".$localization." --productId=".$productId."  --projectId=".$projectId." --instanceId=".$this->instanceId." >/dev/null 2>&1 \n";
    						$solrCommands = $solrCommands . $solrCommand;
    					}
    				}
    			}
    		}
    		
    		if($solrCommands != '')
    		{
    			exec($solrCommands);
    		}
    	}
    	
    	$output->writeln("\n========================================\n");
    	$output->writeln("\nExecuted Following Solr Commands\n");
    	$output->writeln($solrCommands);
    	$output->writeln("\n========================================\n");
    	
    }
}