<?php

namespace OfficeBrain\Bundle\SearchBundle\Manager\Extended;

use Symfony\Component\HttpFoundation\Request;
use OfficeBrain\Bundle\SearchBundle\Manager\AbstractManager\SearchAbstract;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use OfficeBrain\Bundle\SearchBundle\Helper\SearchHelper;
use OfficeBrain\Bundle\SolrBundle\Helper\StandardHelper;
use OfficeBrain\Bundle\SearchBundle\Entity\SaveSearch;
use Symfony\Component\HttpFoundation\Session\Session;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;
use Symfony\Component\Form\FormBuilderInterface;
use OfficeBrain\Bundle\CoreBundle\TwigExtension;

class SolrSearchExtended extends SearchAbstract
{
    protected  $recordPerPage;
    protected  $limitSearch;

    public function __construct($entityManager, $request, $solrManager, $productDetailManager, $categoryManager, $sessionManager, $paginatorManager, $serviceContainer)
    {
    	parent::__construct($entityManager, $request, $solrManager, $productDetailManager, $categoryManager, $sessionManager, $paginatorManager, $serviceContainer);
    	$this->projectSetting = $this->request->get('project_setting');
    	$this->recordPerPage = $this->projectSetting['configuration_rule']['search']['search_page']['record_per_page'];
    	//$this->showLowestPriceInMatchRange = $this->projectSetting['configuration_rule']['search']['search_page']['show_lowest_price_in_match_range'];
    	
    	// Price Range sorting with configuration : START   	
    	$this->priceRangeSorting = isset($this->projectSetting['configuration_rule']['search']['search_page']['price_range_sorting'])?$this->projectSetting['configuration_rule']['search']['search_page']['price_range_sorting']:'';
    	// Price Range sorting with configuration : END
    	$this->request = $request;
    	$this->searchHelper = $serviceContainer->get('office_brain_search_helper');
    	$this->limitSearch = $this->projectSetting['configuration_rule']['search']['search_page']['advance_search']['option']['save_search']['option']['limit_save_recent_search'];
    	$this->productSearchForm = new ProductSearchType();
    	$this->serviceGroupId = $this->projectSetting['service_group_id'];
    	$this->userId = $this->projectSetting['user_id'];
    	$this->projectUserSetting = $this->request->get('project_user_setting');
    	$this->currentLoginUser = $this->projectUserSetting['user_data'];
    	$this->searchArray = '';
    	$this->form = '';
    	$this->highLightImage = '';
    	$this->init();
    	$this->finalArray = array();
    }

    public function init()
    {
    	$this->facetCriteria = array(
    	    'categoryId' => 'yes',
    	    'categoryName' => 'yes',
    	    'supplierId' => 'yes',
    	    'supplierName'=>'yes',
    	    'lineNameId' => 'yes',
    	    'lineName' => 'yes',
    	    'catalogYear' => 'yes',
    	    'priceValidUntil' => 'yes',
    	    'priceCurrency' => 'yes',
    	    'callForPrice' => 'yes',
    	    'priceRange' => 'yes',
    	    'customCategory' => 'Yes',
    	    'productAttribute'=>'yes',
    	    'publicCustomTagText'=>'yes',
    	    'privateCustomTagText'=>'yes',
    	    'colorMapping'=>'yes',
    	    'serviceGroupId'=>'yes',
    	    'serviceGroupIdValue'=> $this->serviceGroupId,
    		'size'=>'yes',
    		'ink'=>'yes',
    		'productionTimeId'=>'yes',
    		'fobId'=>'yes'
    	);
    	$this->solrManager->setSearchCulture($this->cultureCode);
    	 // ,'productAttribute'=>'yes');
    }

    /**
     * @author Employee Id: 4014
     * Description : To get product list from solr
     *
     * @param string $productSearchData
     * @param string $getFacet
     * @param array $searchHelper
     *
     * @return array
     *
     * @throws Exception
     *
     **/
    public function searchResult($productSearchData, $showAllRecords=false, $setSelectedFld="")
    {

    	if($showAllRecords){
            if($setSelectedFld!=""){
                $this->solrManager->setSelectFld($setSelectedFld);
            }

			$selectQuery = $this->solrManager->getCreateQueryInstance();
	    	$selectQuery = $this->solrManager->filterProduct($selectQuery, $productSearchData::toSolrSupportedArray($productSearchData), $showAllRecords,$this->serviceGroupId);
	    	$resultSet = $this->solrManager->getSearchClient()->select($selectQuery);
	    	$selectQuery1 = $this->solrManager->getCreateQueryInstance();
	    	$selectQuery1->setStart(0)->setRows($resultSet->getNumFound());
	    	$selectQuery = $this->solrManager->filterProduct($selectQuery1, $productSearchData::toSolrSupportedArray($productSearchData),$showAllRecords,$this->serviceGroupId);
	    	$pagination = $this->paginatorManager->paginate(array(
	    			$this->solrManager->getSearchClient(), $selectQuery),
	    			$this->request->query->get('page', 1),
	    			$this->request->query->get('per_page', ($resultSet->getNumFound() > 0)?$resultSet->getNumFound():1)
	    	);
		}
		else {
		    //echo get_class($this->solrManager);die;
			$selectQuery = $this->solrManager->getCreateQueryInstance();
			// Price Range sorting with configuration : START
			$selectQuery = $this->solrManager->filterProduct($this->solrManager->getCreateQueryInstance(), $productSearchData::toSolrSupportedArray($productSearchData),false,$this->serviceGroupId,$this->priceRangeSorting);
			//echo "Select Query:<pre>";print_r($selectQuery);die;
			// Price Range sorting with configuration : END
			//echo get_class($this->solrManager->getSearchClient());die;
			//echo "Select Query:<pre>";var_dump($selectQuery);die;
			//echo get_class($this->solrManager->getSearchClient()->select($selectQuery));die;
			$this->highLightImage = $this->solrManager->getSearchClient()->select($selectQuery)->getHighlighting();
			$pagination = $this->paginatorManager->paginate(array($this->solrManager->getSearchClient(), $selectQuery),
					$this->request->query->get('page', 1),
					$this->request->query->get('per_page', $this->recordPerPage)
			);
		}

    /****************************************************************************/
		//$selectQuery = $this->solrManager->filterProduct($this->solrManager->getCreateQueryInstance(), $productSearchData::toSolrSupportedArray($productSearchData));
        /*$pagination = $this->paginatorManager->paginate(array(
                            $this->solrManager->getSearchClient(), $selectQuery),
                            $this->request->query->get('page', 1),
                            $this->request->query->get('per_page', $this->recordPerPage)
                      );*/
		/* $_format = $this->request->get('_format', null);
		if($_format == 'json'){
			return array('search_result_array'=> array_merge(array('data' => $this->searchHelper->formatSolrResult($pagination->getItems()->getArrayCopy() ,$this->highLightImage)), $pagination->getPaginationData()));
		} */
		$formatedSearchResult = $this->searchHelper->formatSolrResult($pagination->getItems()->getArrayCopy(),$this->highLightImage);
		if($this->request->get('custom_search_image_value') && ($this->request->get('custom_search_image_value')!="" && $this->request->get('custom_search_image_value')!=null))
		{
			$formatedSearchResult = $this->prepareVariatinImages($formatedSearchResult,$this->request->get("custom_search_image_value"));
		}
		else
		{
			if($this->request->query->get('color_filter_id') && $this->request->query->get('color_filter_id')!="" && $this->request->query->get('color_filter_id')!="[]")
			{
				$colorId = preg_replace('/[^a-z0-9]/i', '', $this->request->get('color_filter_id', ''));
				$colorName = preg_replace('/[^a-z0-9]/i', '', $this->request->get('colormapping_filter', ''));
				$colorMapping = array($colorId."##".$colorName);
				$formatedSearchResult = $this->prepareVariatinImages($formatedSearchResult,$colorMapping);
			}
		}

		return array('search_result_array'=> array_merge(array('data' => $formatedSearchResult), $pagination->getPaginationData()), 'pagination'=>$pagination);
    }

    public function prepareVariatinImages($formatedSearchResult,$customSearchImageValue)
    {
    	$searchImagesArray = explode("||",$customSearchImageValue);
    	
    	if($searchImagesArray == null)
    	{
    		$searchImagesArray = $customSearchImageValue;
    	}

    	foreach($formatedSearchResult as $prodIndex => $product)
    	{
    		$productColorCount = 0;
    		
//     		foreach($searchImagesArray as $searchImage)
//     		{
//     			$variationIndex = $this->getImageIndex($searchImage,$product["color_mapping_search"]);
//     			if($variationIndex != -1)
//     			{
//     				$productColorCount = $productColorCount + 1;
//     			}
//     			if(empty($formatedSearchResult[$prodIndex]["variation_image_final"]))
//     			{
//     				$formatedSearchResult[$prodIndex]["variation_image_final"] = $product["variation_image_path_txt"][$variationIndex];
//     			}
//     		}
    		
    		$arrayCheck = array();
    		foreach($searchImagesArray as $searchImage)
    		{
    			$variationIndex = $this->getImageIndex($searchImage,$product["color_mapping_search"]);
    			if($variationIndex != -1)
    			{
    				$variationIndex = explode("~~",$variationIndex);
    				if(isset($variationIndex[0]) && isset($variationIndex[1]))
    				{
    					if(!in_array($variationIndex[0],$arrayCheck))
    					{
    						$arrayCheck[] = $variationIndex[0];
    						$productColorCount = $productColorCount + 1;
    					}
    					if(empty($formatedSearchResult[$prodIndex]["variation_image_final"]))
    					{
    						$vrtnIndx = $variationIndex[1];
    						$formatedSearchResult[$prodIndex]["variation_image_final"] = $product["variation_image_path_txt"][$vrtnIndx];
    					}
    				}
    			}
    		}

    		if($productColorCount != 1)
    		{
    			unset($formatedSearchResult[$prodIndex]["variation_image_final"]);
    		}
    	}

    	return $formatedSearchResult;
    }
    
    
    public function getImageIndex($str, array $arr)
    {
    	foreach($arr as $index=>$a) {
    		$masterColorArray = explode('|',$a);
//     		$selectedColor = explode('##',$str);
//     		$masterColorName = explode('##',$masterColorArray[0]);
    		
//     		if(isset($masterColorArray[0]))
//     		{
//     			if( (trim($masterColorArray[0])!='') && (strpos($masterColorArray[0],$str) !== false) )
//     			{
//     				return $index;
//     			}
//     		}
    		
    		if(isset($masterColorArray[1])) 
    		{
    			if( (trim($masterColorArray[1])!='') && (strpos($masterColorArray[1],$str) !== false) )
    			{
    				if(isset($masterColorArray[0]))
    				{
    					return $masterColorArray[0]."~~".$index;
    				}
    				return $index;
    			}
    		}
    	}
    	return -1;
    }
    
    public function searchFilter($productSearchData)
    {
        $facetFields = $this->getFacetFields();
        //$categorySubCategoryList = $this->getAllCategoryList();
        $selectQuery = $this->solrManager->filterProduct($this->solrManager->getCreateQueryInstance(), $productSearchData::toSolrSupportedArray($productSearchData),false,$this->serviceGroupId);
        $selectQuery = $this->solrManager->getFacetQuery($selectQuery, $facetFields);
        $resultSet = $this->solrManager->getSearchClient()->select($selectQuery);
       // echo "<pre>";print_r($resultSet);exit;
        return $this->searchHelper->formatFacetResult($this->entityManager, $resultSet, $this->languageId, null, $productSearchData->getDistributorId(),$this->serviceGroupId);
    }

    private function getFacetFields()
    {
        // TODO currently only category id and product attributes are mapped for facet result more field will come here.
        $facetFields = $this->request->get('facetField', null);
        if ($facetFields == null) {
            return $this->facetCriteria;
        } else {
            $tmpFacetFields = array();
            foreach (explode(',', $facetFields) as $facetField) {
                $tmpFacetFields [$facetField] = 'yes';
            }
            return $tmpFacetFields;
        }
    }

    public function filterProduct()
    {
    }

    /**
     * @author Employee Id: 4532
     * Description : This function is used for get category, sub category list with mapping hierarchy
     *
     *
     * @return array
     *
     * @throws Exception
     *
     **/
    public function getCategorySubCategoryList()
    {
    	//TODO language need to update API

    	$categoryAndSubCategoryList = array();

    	$culture = $this->getCurrentCultureCode();
    	$categoryAndSubCategoryList[] = $this->categoryManager->getList($this->projectSetting['locale_language']);
    	return $categoryAndSubCategoryList[0][$this->projectSetting['locale_language']];
    }

    /**
     * @author Employee Id: 4861
     * Description : Create array of categories
     *
     *
     * @return array
     *
     * @throws Exception
     *
     **/
    public function createIdOfcategories($categoriesId)
    {
    	//TODO language need to update API
    	$categoryIdArray = array();
    	foreach ($categoriesId as $id)
    	{
    		if($id['count'] > 0 ){
    		$categoryIdArray[] = $id['id'];
    		}
    	}
		return $categoryIdArray;
    }
    /**
     * @author Employee Id: 4861
     * Description : Get Images from Id
     *
     *
     * @return array
     *
     * @throws Exception
     *
     **/
    public function getCategoryImagesFromId($categoriesId)
    {
    	return $this->entityManager->getRepository('OfficeBrainCategoryBundle:CategoryMapping')->getCategoryImageById($categoriesId);
    }

    /**
     * @author Employee Id: 4861
     * Description : Format Array
     *
     *
     * @return array
     *
     * @throws Exception
     *
     **/
    public function formatArrayCategoryImages($categoriesId)
    {
    	$categoryIdArray = array();
		foreach ($categoriesId as $id)
    	{
    		$categoryIdArray[$id['pms_id']] = $id['image'];
    	}
		return $categoryIdArray;
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: delete Save search.
     *
     * @param local,id of save search
     *
     * @return json Response
     *
     * @throws NULL
     *
     **/
    public function deleteSaveSearch($saveId)
    {
    	return $this->entityManager->getRepository('OfficeBrainSearchBundle:SaveSearch')->deleteSaveSearch($saveId);

    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: check Save search.
     *
     * @param local,id of save search
     *
     * @return id
     *
     * @throws NULL
     *
     **/
    public function checkSaveSearch($name)
    {
    	$result = $this->entityManager->getRepository('OfficeBrainSearchBundle:SaveSearch')->checkSaveSearch($name,$this->projectSetting['user_id']);
    	if ($result == null) {
    		unset($result);
    		return'Null';
    	} else {
    		unset($result);
    		return 'IsPresent';
    	}

    }


    /**
     * @author Employee Id: 4532
     * Description : This function is used for get current culture code
     *
     *
     * @return culture code
     *
     **/

    public function getCurrentCultureCode()
    {
    	$culture_name = $this->request->attributes->get('_locale');
    	$cultureArray = explode('_',$culture_name);
    	$culture = $cultureArray[0];

    	return $culture;
    }
    /**
     * @author Employee Id: 4861
     * Description : This function is used for get Parent category
     *
     *
     * @return array
     *
     * @throws Exception
     *
     **/
    public function getParentCategoryList()
    {
        $parentCategories = array();
        $categories = $this->getCategorySubCategoryList();
        foreach ($categories as $category) {
            if (isset($category["pms_id"])) {
                $parentCategories[] = array("name"=> $category["cat_name"],"id" => $category["pms_id"]);
            }
        }

        return $parentCategories;
    }

    /**
     * @author Employee Id: 4861
     * Description : This function is used for get array of all paramaters
     *
     *
     * @return array
     *
     * @throws Exception
     *
     **/

    public function getSearchArray()
    {
        $this->searchRequestArray = array();
        $this->mainFilter = $this->request->get("main_filter", "keyword");
        $page = $this->request->get('page', 1);
        $this->searchQuery = trim($this->request->get('search_query', ''));
        if($this->mainFilter == 'supplierName'){
        $this->searchRequestArray['product_search']['supplierName'][] = $this->searchQuery;
        }else{
        $this->searchRequestArray['product_search'][$this->mainFilter] = $this->searchQuery;
        }
        // Added for sort functionality
        //$sortingValArray = explode('::', trim($this->request->get('sort_by', 'bestseller::desc')));
        $sortingValArray = explode('::', trim($this->request->get('sort_by', 'custom_sort::asc')));
        $sortValArray = array();

        if (isset($sortingValArray)) {
            if (isset($sortingValArray[0]) && isset($sortingValArray[1])) {
                $sortValArray['field'] = $sortingValArray[0];
                $sortValArray['order'] = $sortingValArray[1];
            }
        }
        // End add for sort functionality
        	$this->searchRequestArray['product_search']['serviceGroupId'] = $this->serviceGroupId;
        	//$this->searchRequestArray['product_search']['min_price_'.$this->serviceGroupId.'_f'] = trim($this->request->query->get('min_price', ''));
        	//$this->searchRequestArray['product_search']['max_price_'.$this->serviceGroupId.'_f'] = trim($this->request->query->get('max_price', ''));
        $this->searchRequestArray['product_search']['min_price'] = trim($this->request->get('min_price', ''));
        $this->searchRequestArray['product_search']['max_price'] = trim($this->request->get('max_price', ''));
        $this->searchRequestArray['product_search']['quantity'] = trim($this->request->get('quantity', ''));
        $this->searchRequestArray['product_search']['categoryId'] = is_array($this->request->get('category_filter', '')) ? $this->request->get('category_filter', '') : trim($this->request->get('category_filter', ''));

        $this->searchRequestArray['product_search']['inactiveCategoryId'] = $this->request->get('inactive_category_id', '');

        $this->searchRequestArray['product_search']['campaignId'] = is_array($this->request->get('campaign_filter', '')) ? $this->request->get('campaign_filter', '') : trim($this->request->get('campaign_filter', ''));
        $this->searchRequestArray['product_search']['displayCampaignProduct'] = trim($this->request->get('display_campaign_product', '0'));
        $this->searchRequestArray['product_search']['brandId'] = is_array($this->request->get('brand_filter', '')) ? $this->request->get('brand_filter', '') : trim($this->request->get('brand_filter', ''));
        
        $this->searchRequestArray['product_search']['sizeId'] = is_array($this->request->get('size_filter', '')) ? $this->request->get('size_filter', '') : trim($this->request->get('size_filter', ''));
        $this->searchRequestArray['product_search']['inkId'] = is_array($this->request->get('ink_filter', '')) ? $this->request->get('ink_filter', '') : trim($this->request->get('ink_filter', ''));
        $this->searchRequestArray['product_search']['productionTimeId'] = is_array($this->request->get('production_time_filter', '')) ? $this->request->get('production_time_filter', '') : trim($this->request->get('production_time_filter', ''));
        $this->searchRequestArray['product_search']['fobId'] = is_array($this->request->get('fob_filter', '')) ? $this->request->get('fob_filter', '') : trim($this->request->get('fob_filter', ''));
        
        $this->searchRequestArray['product_search']['supplierId'] = trim($this->request->get('supplier_filter', ''));
        $this->searchRequestArray['product_search']['priceCurrency'] = is_array($this->request->get('price_currency', '')) ? $this->request->get('price_currency', '') : trim($this->request->get('price_currency', ''));
        $this->searchRequestArray['product_search']['rating'] = trim($this->request->get('rating_filter', ''));
        $this->searchRequestArray['product_search']['priceValidUntil'] = is_array($this->request->get('price_valid_until', '')) ? $this->request->get('price_valid_until', '') : trim($this->request->get('price_valid_until', ''));
        $this->searchRequestArray['product_search']['lineNameId'] = is_array($this->request->get('line_name_id', '')) ? $this->request->get('line_name_id', '') : trim($this->request->get('line_name_id', ''));
        $this->searchRequestArray['product_search']['catalogYear'] = is_array($this->request->get('catalogyear_filter', '')) ? $this->request->get('catalogyear_filter', '') : trim($this->request->get('catalogyear_filter', ''));
        $this->searchRequestArray['product_search']['tag'] = is_array($this->request->get('tag_filter', '')) ? $this->request->get('tag_filter', '') : trim($this->request->get('tag_filter', ''));
        $this->searchRequestArray['product_search']['attribute'] = trim($this->request->get('attribute_filter', ''));
        
        if($this->request->get('custom_search_image_value') && ($this->request->get('custom_search_image_value')!="" && $this->request->get('custom_search_image_value')!=null))
        {
        	$this->searchRequestArray['product_search']['colorMapping'] = explode("||",$this->request->get('custom_search_image_value', ''));
        }
        else
        {
        	if($this->request->query->get('color_filter_id') && $this->request->query->get('color_filter_id')!="" && $this->request->query->get('color_filter_id')!="[]")
        	{
        		$colorId = preg_replace('/[^a-z0-9]/i', '', $this->request->get('color_filter_id', ''));
        		$colorName = preg_replace('/[^a-z0-9]/i', '', $this->request->get('colormapping_filter', ''));
        		$this->searchRequestArray['product_search']['colorMapping'] = array($colorId."##".$colorName);
        	}
        	else {
        		$this->searchRequestArray['product_search']['colorMapping'] = trim($this->request->get('colormapping_filter', ''));
        	}
        }
        
        $this->searchRequestArray['search']['query'] = $this->searchQuery;
        $this->searchRequestArray['search']['main_filter'] = $this->mainFilter;
        $this->searchRequestArray['search']['culture'] = $this->projectSetting['locale_language'];
        $this->searchRequestArray['search']['save_search_name'] = trim($this->request->get('save_search_name', ''));
        $this->searchRequestArray['render_model'] = trim($this->request->get('render_model', ''));
        $this->searchRequestArray['product_search']['similarSku'] = trim($this->request->get('similar_sku', ''));
        $this->searchRequestArray['product_search']['productId'] = trim($this->request->get('product_id', ''));
        $this->searchRequestArray['product_search']['categoryTagId'] = $this->request->get('tag_category_id', '');
        $this->searchRequestArray['product_search']['categoryTag'] = $this->request->get('tag_id', '');
        $this->searchRequestArray['product_search']['originalSupplierId'] = is_array($this->request->get('original_supplier_filter', '')) ? $this->request->get('original_supplier_filter', '') : trim($this->request->get('original_supplier_filter', ''));
        $this->searchRequestArray['product_search']['relatedProductIds'] = is_array($this->request->query->get('related_product_ids', '')) ? $this->request->query->get('related_product_ids', '') : trim($this->request->query->get('related_product_ids', ''));
        $this->searchRequestArray['product_search']['recentProductIds'] = is_array($this->request->query->get('recent_product_ids', '')) ? $this->request->query->get('recent_product_ids', '') : trim($this->request->query->get('recent_product_ids', ''));
        if(!empty($this->request->query->get('search_type')))
        {
        	$this->searchRequestArray['product_search']['searchType'] = $this->request->query->get('search_type', 'ALL');
        }
        if(isset($this->userId)){
        $this->searchRequestArray['product_search']['distributorId'] = $this->userId;
        }
        $this->searchRequestArray['product_search']['quoteSearch'] = $this->request->get('quote_search', '');


        if ($this->request->get('sku') != '') {
            $this->searchRequestArray['product_search']['sku'] = trim($this->request->get('sku', ''));
        }
        $this->searchRequestArray['product_search']['sort'] = $sortValArray;
        $this->searchRequestArray['product_search']['instanceId'] = $this->instanceId;

        if ($this->request->get('supplier_name') != '') {
            $this->searchRequestArray['product_search']['supplierName'] = is_array($this->request->get('supplier_name', '')) ? $this->request->get('supplier_name', '') : trim($this->request->get('supplier_name', ''));
        }
        $this->request->query->set($this->request->get('main_filter', 'keyword'), $this->request->get('search_query'));
        return $this->searchRequestArray;
    }

    /**
     * @author Employee Id: 4861
     * Description : This function is used to convert Array To Json
     *
     *
     * @return array
     *
     * @throws Exception
     *
     **/

    public function convertArrayToJson($searchArray)
    {
        return json_encode($searchArray);
    }

    /**
     * @author Employee Id: 4861
     *
     * Description : This function is used to convert Array To Json
     *
     * @return array
     *
     * @throws Exception
     *
     **/

    public function convertJsonToArray($saveSearchArray)
    {
        return json_decode($saveSearchArray);
    }

    public function getQueryStringRecentSearch($array)
    {
    	unset($array['save_search_name']);
        $this->queryStringRaw = '?';
        if ($array != null) {
            $this->queryStringRaw .= http_build_query($array) . "\n";
        }
        return $this->queryStringRaw;
    }

    public function getQueryString($array)
    {
        $this->queryStringRaw = '?';
        if ($array != null) {
            $this->queryStringRaw .= http_build_query($array) . "\n";
        }
        return $this->queryStringRaw;
    }

    /**
     * @author Employee Id: 4861
     *
     * Description : This function is used for set all search paramaters in database
     *
     *
     * @return array
     *
     * @throws Exception
     *
     **/

    public function findSaveSearchInRecentSearch($searchQueryHashkey)
    {
    	$recentSearchData = $this->sessionManager->get($this->sessionRecentSearchKey);
        if(count($recentSearchData)) {
	        foreach ($recentSearchData as $key => $value) {
	        	if($value['hash_key'] == $searchQueryHashkey) {
	        		unset($recentSearchData[$key]);
	        	}
	        }
        }
        $this->sessionManager->set($this->sessionRecentSearchKey, $recentSearchData);
    }

    /**
     * @author Employee Id: 4861
     * Description : This function is used for set all search paramaters in database
     *
     *
     * @return array
     *
     * @throws Exception
     *
     **/

    public function setSaveSearch($searchArray)
    {
    	$this->getArray = $this->convertArrayToJson($searchArray);
    	$tempArray = $searchArray;
    	unset($tempArray['save_search_name']);
    	$saveSearchId = $this->entityManager->getRepository('OfficeBrainSearchBundle:SaveSearch')->setSaveSearchDB($this->getArray, $searchArray['save_search_name'], $this->projectSetting['user_id'],md5($this->getQueryString($tempArray)));
    	$this->findSaveSearchInRecentSearch(md5($this->getQueryString($tempArray)));
    	return $saveSearchId;
    }

    /**
     * @author Employee Id: 4861
     *
     * Description : This function is used for get all search query form database
     *
     * @return array
     *
     * @throws Exception
     *
     **/

    public function getAllSaveSearch()
    {
        $this->saveSearchArray = $this->entityManager->getRepository('OfficeBrainSearchBundle:SaveSearch')->getAllSaveSearch($this->projectSetting['user_id']);

        $this->returnSaveSearchInArray($this->saveSearchArray);
        return $this->finalArray;
    }


    /**
     * @author Employee Id: 4861
     *
     * Description : This function is used common function of save search
     *
     * @return array
     *
     * @throws Exception
     *
     **/

    public function returnSaveSearchInArray($saveSearchArray)
    {
        foreach ($saveSearchArray as $saveSearch) {
            $this->getArray = $this->convertJsonToArray($saveSearch['jsonData']);
            $this->finalArray[] = array('id'=>$saveSearch['id'], 'title'=>$saveSearch['searchTitle'], 'queryString'=> $this->getQueryString($this->getArray));
        }
        unset($saveSearchArray);
        unset($this->getArray);

        return $this->finalArray;
    }

    /**
     * @author Employee Id: 4861
     *
     * Description : This function is used for get search query form database
     *
     * @return array
     *
     * @throws Exception
     *
     **/

    public function getSaveSearch()
    {
        $this->saveSearchArray = $this->entityManager->getRepository('OfficeBrainSearchBundle:SaveSearch')->getSaveSearch($this->projectSetting['user_id'], $this->limitSearch);

        $this->returnSaveSearchInArray($this->saveSearchArray);

        return $this->finalArray;
    }

    /**
     * @author Employee Id: 4861
     * Description : This function is used for set Recent search in session
     *
     * @return array
     *
     * @throws Exception
     *
     **/

    public function setRecentSearch()
    {
    	$searchQuery = $this->request->query->get('search_query', null);

    	if($searchQuery) {
	        $jsonArray = $this->getQueryStringRecentSearch($this->request->query->all());
	        if($this->userId){
	        $this->isAlreadySavedSearch = $this->entityManager->getRepository('OfficeBrainSearchBundle:SaveSearch')->findSaveSeach(md5($jsonArray), $this->userId);
	        }else{
	        	$this->isAlreadySavedSearch = '';
	        }

			if (!$this->isAlreadySavedSearch) {
				$recentSearch = $this->sessionManager->get($this->sessionRecentSearchKey);
				if(!is_array($recentSearch)){
					$recentSearch= null;
				}
	        	$sessionData = $this->addArrayToSession($recentSearch, $jsonArray, $searchQuery);
	        	$this->sessionManager->set($this->sessionRecentSearchKey, $sessionData);
	       	}
    	}
     }

    public function addArrayToSession($recentSearchData, $jsonArray, $name)
    {
        if ($recentSearchData == null) {
            $recentSearchData= array();
            $value= array();
        }

        if(is_array($recentSearchData)) {
        	$hashKey = md5($jsonArray);
	        if(array_column($recentSearchData, 'hash_key')){
	        	$value =array_column($recentSearchData, 'hash_key');
	        }
	        if (!in_array($hashKey, $value) && !in_array($name, $value)) {
	        	$recentSearchData = array_reverse($recentSearchData);
	            if (count($value)>= $this->limitSearch) {
	                array_shift($recentSearchData);
	                array_push($recentSearchData, array('name' => $name, 'value'=> $jsonArray, 'hash_key'=> $hashKey));
	            } else {
	                array_push($recentSearchData, array('name' => $name, 'value'=> $jsonArray, 'hash_key'=> $hashKey));
	            }
	        }
	        else
	        {
	        	foreach ($recentSearchData as $key => $val)
	        	{
	        		if($val['name']==$name)
	        		{
	        			$temp = $recentSearchData[$key];
	        			unset($recentSearchData[$key]);
	        			array_unshift($recentSearchData,$temp);
	        		}
	        	}
	        	return $recentSearchData;
	        	 
	        }
	        unset($value);
	        unset($hashKey);
	        unset($jsonArray);
	        return array_reverse($recentSearchData);
        }
        return $recentSearchData;
    }

    public function getFilterAttributeValueId($searchQuery)
    {
    	$attrVal = array();
    	$attrValueId = '';
    	if ($searchQuery) {
    		$attrVal = json_decode($searchQuery);
    		if (count($attrVal) == 1) {
				$attrValueId = $attrVal[0];
    		}
    	}

    	return $attrValueId;
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: Bind request paramater with form
     *
     * @param Array paramaters
     *
     * @return NULL
     *
     * @throws NULL
     */
    public function prepareSearchForm()
    {
    	$searchQuery = $this->getSearchArray();
    	$this->productSearchData = new ProductSearchData($this->entityManager, $this->languageId);
    	$this->form = $this->formFactory->create($this->productSearchForm, $this->productSearchData, array('csrf_protection' => false));
    	$this->form->bind($searchQuery['product_search']);
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: call all query paramaters and bind them with form
     *
     * @param Array paramaters
     *
     * @return NULL
     *
     * @throws NULL
     */
    public function searchService($showAllRecords = false)
    {
    	$this->prepareSearchForm();
    	$this->responseArray = $this->callSearchService($showAllRecords);
    	return $this->responseArray;
    }
    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: call all query paramaters and bind them with form
     *
     * @param Array paramaters
     *
     * @return NULL
     *
     * @throws NULL
     */
    public function searchFilterService($showAllRecords = false)
    {
    	$this->prepareSearchForm();
    	$this->responseArray = $this->callSearchFilterService($showAllRecords);
    	return $this->responseArray;
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: call all query paramaters and bind them with form for advance search
     *
     * @param Array paramaters
     *
     * @return NULL
     *
     * @throws NULL
     */
    public function advanceSearchService()
    {
    	$this->prepareSearchForm();
    	$this->responseArray = $this->callAdvanceSearchService();
    	return $this->responseArray;
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: call all query paramaters and bind them with form
     *
     * @param Array paramaters
     *
     * @return NULL
     *
     * @throws NULL
     */
    public function callSearchService($showAllRecords)
    {
    	if ($this->form->isValid()) {
    	    $this->searchArray = $this->searchResult($this->form->getData(),$showAllRecords);
    	}
    	return $this->searchArray;
    }
    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: call all query paramaters and bind them with form
     *
     * @param Array paramaters
     *
     * @return NULL
     *
     * @throws NULL
     */
    public function callSearchFilterService($showAllRecords)
    {
    	if ($this->form->isValid()) {
    		$this->searchArray = $this->searchFilter($this->form->getData(),$showAllRecords);
    	}
    	return $this->searchArray;
    }
    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: call all query paramaters and bind them with form advance search
     *
     * @param Array paramaters
     *
     * @return NULL
     *
     * @throws NULL
     */
    public function callAdvanceSearchService()
    {
    	if ($this->form->isValid()) {
    		$this->advanceSearchArray = $this->searchFilter($this->form->getData());
    	}
    	return $this->advanceSearchArray;
    }

    /**
     * @author Employee Id: 4505
     * Description : To get product list from solr
     *
     * @param string $productSearchData
     * @param string $getFacet
     * @param array $searchHelper
     *
     * @return array
     *
     * @throws Exception
     *
     **/
    public function getSolrProductTags($sku,$productId)
    {
        $selectQuery = $this->solrManager->filterProductForTags($this->solrManager->getCreateQueryInstance(), $sku,$productId);
        $solrObj = $this->solrManager->getSearchClient()->select($selectQuery);
        $response = (array)json_decode($solrObj->getResponse()->getBody());
        $response = (array)$response['response'];
        if(key_exists(0, $response['docs']))
        {
            return (array)$response['docs'][0];
        }
        else
        {
            return array();
        }
    }
    
    /**
     * @author Employee Id: 10175
     * Description : To get ProductData with which minPrice,image to show on listing page;this is data with condtion on searchProductRow.html 
     *
     * @param string $productSearchData
     * 
     * @return array
     *
     * @throws Exception
     *
     **/
    public function getProductRowDataToShowMobileAPI($productAry, $productImageBaseUrl, $colorSwatchBaseUrl, $attributeId=null)
    {
    	
  		if( is_array($productAry) ){
  			
  			$qty = $this->request->query->get('quantity',null);  			
  			foreach ( $productAry as $key=>$product ) {
  				
  				/**************** [START]SET min_price_to_show ************************/
  				$minPrice = null;  				
  				if( $qty &&  $qty > 0 ) { // if Quantity is set then....
  					for ($range=1;$range<=15;$range++){
  						if ( $this->serviceGroupId > 0 && isset( $product['min_qty'. '_'.$this->serviceGroupId.'_' . $range] ) ) {
  							if ( $qty >= $product['min_qty'. '_'.$this->serviceGroupId.'_' . $range] && $qty <= $product['max_qty'. '_'.$this->serviceGroupId.'_' . $range] && $product['price'. '_'.$this->serviceGroupId.'_' . $range] > 0 ){
  								$minPrice = $product['price'. '_'.$this->serviceGroupId.'_' .$range];
  							}
  						}else if ( isset( $product['min_qty'. '_' . $range] ) ){
  							if ( $qty >= $product['min_qty'. '_' . $range] && $qty <= $product['max_qty'. '_' . $range] && $product['price'. '_' . $range] > 0 ){
  								$minPrice = $product['price'. '_' . $range];
  							}
  						}  						
  					}
  				} else  {
  					if ( $this->serviceGroupId > 0  &&  isset( $product['min_price'. '_'.$this->serviceGroupId] ) ) {
  						$minPrice = $product['min_price'. '_'.$this->serviceGroupId];
  					}else if( $this->serviceGroupId > 0  && isset ( $product['min_price'. '_'.$this->serviceGroupId] ) ){
  						$minPrice = (isset($product['min_price'])?$product['min_price']:null);
  					}else {
  						$minPrice = (isset($product['min_price'])?$product['min_price']:null);
  					}
  					
  				}
  				$productAry[$key] ['min_price_to_show'] = $minPrice;
  				/**************** [OVER]SET min_quantity to show ************************/
  				
  				
  				/**************** [START]SET min_quantity to show ************************/
  				$minQuantity = null;
  				if ( $qty !== null ){
  					$minQuantity = $qty;  					
  				}else if ( isset( $product['min_qty_1'] ) && $product['min_qty_1']!='' ){
  					$minQuantity = $product['min_qty_1'];
  				}
  				$productAry[$key] ['min_qunatity_to_show'] = $minQuantity;
  				/**************** [OVER]SET min_quantity to show ************************/
  				
  				
  				/**************** [START]SET product_image to show ************************/
  				$productImageUrl = $productThumbImageUrl = '';
  				
  				if( $attributeId !== null && $attributeId != '' ){
  					$img = Extension::productImageUrl($attributeId,$product['variation_image_path_txt'],$product['variation_image_id_ss']);
  					if( $img != '' ) {
  						$productImageUrl = $img;
  						$productThumbImageUrl = Extension::product_thumb_image_url($attributeId,$product['variation_image_path_txt'],$product['variation_image_id_ss']);
  					}else{
  						$productImageUrl = $product['image_path'];
  						$productThumbImageUrl = $product['image_thumb_path'];
  					}
  				} else if ( isset( $product['color_search_image'] ) && $product['color_search_image'] != '' ){
  					$productImageUrl = $productImageBaseUrl . $product['color_search_image'];
  				} else {
  					$productImageUrl = $product['image_path'];
  					$productThumbImageUrl = $product['image_thumb_path'];
  				}
  				$productAry[$key] ['product_image_to_show'] = $productImageUrl;
  				$productAry[$key] ['product_thumb_image_to_show'] = $productThumbImageUrl;
  				
  				/**************** [OVER]SET product_image to show ************************/
  				
  				/**************** [START]SET color panel image url to show ************************/
  				$colorPanel = null;
  				if( isset( $product['variation_image_id_ss'] ) && count ( $product['variation_image_id_ss'] ) > 0 ) {
  					foreach ( $product['variation_image_id_ss'] as $swatchCode){
  						$colorPanel[] = $colorSwatchBaseUrl.$swatchCode.'.jpg';
  					}
  				}
  				$productAry[$key]['color_panel_to_show'] = $colorPanel;
  				/**************** [OVER]SET color panel image url to show ************************/
  				
  				/**************** [START]SET Quantity Box to show ************************/
  				$quantityBox = null;
  				$callForPrice = isset($product['call_for_price'])?$product['call_for_price']:'no';
  				for ($range=1;$range<=15;$range++){
  					$tmpQtyBox = null; 
  					if ( $this->serviceGroupId > 0 && isset( $product['min_qty'. '_'.$this->serviceGroupId.'_' . $range] ) ) {
  						$thisMinQty = 'min_qty'. '_'.$this->serviceGroupId.'_' . $range;
  						$thisMaxQty = 'max_qty'. '_'.$this->serviceGroupId.'_' . $range;
  					}else if ( $this->serviceGroupId > 0 && (!isset( $product['min_qty'. '_'.$this->serviceGroupId.'_' . $range] )) ) {
  						$thisMinQty = 'min_qty'. '_' .$range;
  						$thisMaxQty = 'max_qty'. '_' .$range;
  					}else{
  						$thisMinQty = 'min_qty'. '_' .$range;
  						$thisMaxQty = 'max_qty'. '_' .$range;
  					}
  					
  					if ( $this->serviceGroupId > 0 && isset( $product['price'. '_'.$this->serviceGroupId.'_' . $range] ) ) {
  						$thisPrice = 'price'. '_'.$this->serviceGroupId.'_' . $range;
  					}else if ( $this->serviceGroupId > 0 && (!isset( $product['price'. '_'.$this->serviceGroupId.'_' . $range] )) ) {
  						$thisPrice = 'price'. '_' .$range;
  					}else{
  						$thisPrice = 'price'. '_' .$range;
  					}	
  					
  					if( isset( $product[$thisPrice] ) ) {
  						$tmpQtyBox['price'] = $product[$thisPrice];
  					}  					
  					if( isset( $product[$thisMinQty] ) ) {
  						$tmpQtyBox['min_qty'] = $product[$thisMinQty];
  						$tmpQtyBox['max_qty'] = ((isset($product[$thisMaxQty])&& $product[$thisMaxQty]<999999)?$product[$thisMaxQty]:null); 
  					}else{
  						break;
  					}
  					
  					if ( $tmpQtyBox ) $quantityBox[] = $tmpQtyBox;
  				}
  				$productAry[$key]['quantity_box_to_show'] = $quantityBox;  				
  				/**************** [OVER]SET Quantity Box to show ************************/
  				
  			}
  		}
  		return $productAry;
    }
    
    public function setRecordPerPage($recordPerPage) {
    	$this->recordPerPage = $recordPerPage;
    }
    
    public function solrSync($solrSyncStatusOfSupplier,$supplierId,$culture) {
    	$return  = array();
    	$status = $this->request->get('status');
    	$environment = $this->serviceContainer->getParameter('kernel.environment');
    	$return['message'] = 'Please check status with add status parameter';

    	if ($supplierId > 0) {
    		if (!($solrSyncStatusOfSupplier > 0)) {
    			$kernelRootDir = 'php '.$this->serviceContainer->getParameter('subshop_media_upload_location')['kernel_root_dir'];
    			$cmd = $kernelRootDir.DIRECTORY_SEPARATOR.'console office_brain:solr:sync:product --projectId='.$this->projectSetting['project_id'].' --culture='.$culture.' --instanceId='.$this->projectSetting['instance_id'].' --supplierId='.$supplierId.' --env="'.$environment.'" > /dev/null 2>/dev/null &';
    			exec($cmd);
    			unset($return['link']);		
    			
    			$return['status'] = 'success';
    			//$return['success_message'] = 'Solr Sync started for supplier id - '.$supplierId;
    			$return['success_message'] = 'Solr Sync started';
    			$return['cmd'] = $cmd;
    		} else
    		{
    			$return['status'] = 'failure';
    			//$return['error_message'] = 'Solr Sync already running for for supplier id - '.$supplierId;
    			$return['error_message'] = 'Solr Sync already running';
    		}
    	}

    	return $return;
    }
    
    public function getCultureCode($countryId,$languageId,$countries)
    {
    	$solrKeyCountryCode = '';
    	$solrKeyLanguageCode = '';
    	
    	/* Decide country and language */
    	if(is_array($countries) && (!(empty($countries))))
    	{
    		foreach($countries as $countryCode => $countryData)
    		{
    			/* Decide country code */
    			if(isset($countryData['id']) && isset($countryId))
    			{
    				if($countryData['id'] == $countryId)
    				{
    					$solrKeyCountryCode = $countryCode;
    				}
    			}
    			/* Decide language code */
    			 
    			if(isset($countryData['language']) && is_array($countryData['language']) && (!(empty($countryData['language']))))
    			{
    				foreach($countryData['language'] as $languageCode => $languageId)
    				{
    					if($languageId == $languageId)
    					{
    						$solrKeyLanguageCode = $languageCode;
    					}
    				}
    			}
    		}
    	}
    	$solrKeyCulture = $solrKeyLanguageCode."_".$solrKeyCountryCode;
    	return $solrKeyCulture;
    }
    
    public function getSolrSyncStatusSupplierCulture($subShopThemeManager,$supplierId,$solrKeyCulture,$instanceId)
    {
    	$subshopInstanceMeta = $subShopThemeManager->getSubShopInstanceKey('solr_sync_status_of_supplier_'.$supplierId.'_'.$solrKeyCulture, $instanceId);
    	if(is_object($subshopInstanceMeta))
    	{
    		$solrSyncStatusOfSupplier = $subshopInstanceMeta->getMetaValue();
    	}
    	else
    	{
    		$solrSyncStatusOfSupplier = 0;
    	}
    	return $solrSyncStatusOfSupplier;
    }
}
