<?php

namespace OfficeBrain\Bundle\SolrBundle\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 OfficeBrain\Bundle\SolrBundle\Helper\StandardHelper;
use Sensio\Bundle\GeneratorBundle\Command\Helper\DialogHelper;
use OfficeBrain\Bundle\SolrBundle\SearchServices\ProductService;
use Doctrine\ORM\Query\ResultSetMapping;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;

/**
 * Sync product Category data command
 *
 * @author OfficeBrain 3916 <info@officebrain.com>
 */
class SyncDeleteProductCommand extends ContainerAwareCommand
{
    CONST COMMAND_NAME = 'office_brain:solr:sync:delete-product';
    CONST PRODUCT_CACHE_CLIENT = 'product';

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName(self::COMMAND_NAME)
            ->setDescription('Command to delete product data')
            ->setDefinition(array(
                new InputOption('projectId', null, InputOption::VALUE_REQUIRED, 'project Id'),
                new InputOption('culture', '', InputOption::VALUE_OPTIONAL, 'Supported search culture.'),
                new InputOption('productId', '', InputOption::VALUE_OPTIONAL, 'Enter product id which you want to delete. Use comma seperator for multiple product id\'s.'),
                new InputOption('instanceId', null, InputOption::VALUE_OPTIONAL, 'Enter instance id for instance wise product Id'),
                new InputOption('productSku', '', InputOption::VALUE_OPTIONAL, 'Enter product sku which you want to delete. Use comma seperator for multiple product sku\'s.'),
                new InputOption('supplierId', '', InputOption::VALUE_OPTIONAL, 'Enter supplier id which you want to delete.'),
                new InputOption('isFeature', '', InputOption::VALUE_OPTIONAL, 'Enter yes which you want to delete feature product.'),
                new InputOption('isOnlyCache', '', InputOption::VALUE_OPTIONAL, 'Enter 1 which you want to delete redis product.'),
            ))
            ->setHelp(<<<EOT
The <info>office_brain:solr:sync:delete-product</info> command helps you to delete products into solar schema.
EOT
            );
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $startAt = microtime(true);
        $culture = $input->getOption('culture', null);
        $productId = $input->getOption('productId', null);
        $instanceId = $input->getOption('instanceId', null);
        $productSku = $input->getOption('productSku', null);
        $supplierId = $input->getOption('supplierId', null);
        $isFeature = $input->getOption('isFeature', 'no');
        $isOnlyCache = $input->getOption('isOnlyCache', '0');

        if ($culture == null) {
            $output->writeln("Please provide a culture !");
            return;
        }
        
        /*if ($productId == '' && $productSku == '' && $supplierId == '') {
            $output->writeln("You didn't set any of the parameter which is helpful for delete products!");
            return;
        }*/
        
        if (empty($instanceId)) {
            $instanceId=1;
        }
        $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 );
        
        $filterBy = array();
        if ($instanceId != '' && $instanceId > 0 ) {
            $filterBy['instance_id'] = $instanceId;
        }

        $productIdList = array();
        if ($productId != '') {
            if (strpos($productId, ',')) {
                $productIdList = explode(',', $productId);
            } else {
                $productIdList = array($productId);
            }
        }

        $productSkuList = array();
        if ($productSku != '') {
            if (strpos($productSku, ',')) {
                $productSkuList = explode(',', $productSku);
            } else {
                $productSkuList = array($productSku);
            }
        }

        $supplierIdList = array();
        if ($supplierId != '') {
            if (strpos($supplierId, ',')) {
                $supplierIdList = explode(',', $supplierId);
            } else {
                $supplierIdList = array($supplierId);
            }
        }

        
        if (count($productIdList) > 0) {
            $filterBy['product_id'] = $productIdList;
        }
        if (count($productSkuList) > 0) {
            $filterBy['sku'] = $productSkuList;
        }
        if (count($supplierIdList)) {
            $filterBy['supplier_id'] = $supplierIdList;
        }
        $isFeature=strtolower($isFeature);
        if ($isFeature != '' && $isFeature=='yes') {
            $filterBy['isFeature'] = $isFeature;
        }
        
        $productSearchClient = $this->getContainer()->get('office_brain_solr.product_search');
        //$connection = $this->getContainer()->get('office_brain_search_engine.pdo')->getConnection();

        if ($culture !== null) {
            $productSearchClient->setSearchCulture($culture);
        }

        $productSearchServices = $this->getContainer()->get('office_brain_solr.product_search');
        $productSearchServices->setSearchCulture($culture);

        $selectQuery = $productSearchServices->getCreateQueryInstance();
        $selectQuery = $productSearchServices->filterProduct($selectQuery, $filterBy);

        $resultSet = $productSearchServices->getSearchClient()->select($selectQuery);

        $selectQuery1 = $productSearchServices->getCreateQueryInstance();
        $selectQuery1->setStart(0)->setRows($resultSet->getNumFound());
        $selectQuery1 = $productSearchServices->filterProduct($selectQuery1, $filterBy);

        $allResultSet = $productSearchServices->getSearchClient()->select($selectQuery1);
        if ($allResultSet->getNumFound() > 0) {
            $count = 0;
            $update = $productSearchClient->getCreateUpdateInstance();
            foreach ($allResultSet->getDocuments() as $document) {
                //echo $count . ' DOCUMENT ID:: ' . $document->id . "\n";
                $count++;
                // add the delete id and a commit command to the update query
                $this->deleteCache($document->product_id_i,$culture);
                if($isOnlyCache!=1)
                {
                    $update->addDeleteById($document->id);
                    $update->addCommit();
                }
            }

            $updateResult = $productSearchServices->commitBatch($update);

            echo "===== Delete Product Summary =====\n";
            echo 'No of records processes: ' . $count . "\n";
            echo '=====  PROCESS COMLETED =====' . "\n";
        } else {
            echo 'No record found for delete operation!' . "\n";
        }

        $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");

    }

    public function deleteCache($productId=0,$culture)
    {
        if(!RedisCacheService::isCacheEnable())
        {
            return null;
        }
        $cacheClient=RedisCacheService::create(null,self::PRODUCT_CACHE_CLIENT);
        echo "===========$productId.':*'.$culture==========";
        $cacheClient->removeCacheByPrefix($productId.':*'.$culture);
    }
}