<?php

namespace OfficeBrain\Bundle\SearchBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Translation\Translator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Doctrine\ORM\Query\ResultSetMapping;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;
use OfficeBrain\Bundle\CategoryBundle\Entity\CultureCategory;
use OfficeBrain\Bundle\ProductBundle\Entity\CultureAttributeMaster;
use OfficeBrain\Bundle\ProductBundle\Entity\AttributeValues;
use OfficeBrain\Bundle\SearchBundle\Helper\SearchHelper;
use OfficeBrain\Bundle\SolrBundle\Helper\StandardHelper;
   /**
    * Default Search Controller
    *
    * @author Employee Id: 410175
    *
    * Desciption: This is a search controler returns search results
    *
    * @param NULL
    *
    * @return Html Response
    *
    * @throws NULL
    *
    * @Route("/api/v1/{_locale}", defaults={"_format" = "json"})
    */
class ApiSearchController extends SearchController
{
	const SUCCESS = 'success';
	const ERROR = 'error';
	const SUCCESS_CODE = 1;
	const ERROR_CODE = 0;
	
    /**
     *
     * @author Employee Id: 410175
     *
     * Desciption: To set member variables default value
     *
     * @param NULL
     *
     * @return null
     *
     * @throws NULL
     **/
    
    public function __construct()
    {
        parent::__construct ();
		$this->imageBaseUrl = null;
		$this->colorImageBaseUrl = null;
		$this->searchConfig = null;
    }
    
    /**
     *
     * @author Employee Id: 410175
     *
     * Desciption: To unset member variables
     *
     * @param NULL
     *
     * @return null
     *
     * @throws NULL
     */
    public function __destruct()
    {
		parent::__destruct ();		
		unset ( $this->imageBaseUrl );
		unset ( $this->colorImageBaseUrl );
		unset ( $this->searchConfig );
    }

    /**
     *
     * @author Employee Id: 410175
     *
     * Desciption: Create various objects required action in this class
     *
     * @param NULL
     *
     * @return NULL
     *
     * @throws NULL
     */
    public function initAction()
    {
    	parent::initAction ();
		$this->userId = $this->projectSetting ['user_id'];		
		$this->imageBaseUrl = $this->container->getParameter ( 'product_image.base_url' );
		$this->colorImageBaseUrl = $this->container->getParameter ( 'api.color_image_base_url' );
		$this->baseURL = $this->container->getParameter ( 'base_url' );
		$this->wishListManager = $this->get ( 'office_brain_wish_list_manager' );
		$this->searchConfig = $this->projectSetting ['access_rule'] ['search'] ['option'] ['search_filter'] ['option'];

    }
	
	
	/**
	 *
	 * @author Employee Id: 4861
	 *
	 * Desciption: Perform search based on search query in selected culture
	 *
	 * @param string search_query
	 *
	 * @return Html/json Response
	 *
	 * @throws if result found search result page else no record found error
	 *
	 * @Route("/search", name="office_brain_search_bundle_search_api")
	 * 
	 * @ApiDoc(
     *      resource=true,
     *      section="Search",
     *      description="Get Product Data By filter/search.",
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      },
     *      requirements={     
     *             {"name"="_locale", "dataType"="string", "required"=true, "default"="en_us"},
     *             {"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *             {"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *             {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *             {"name"="main_filter", "dataType"="string","description"="set 'keyword' as default value"},
     *      	   {"name"="search_query","dataType"="string","description"="Search Keyword"}
     *      },
     *      input = {
     *      	"class" = "OfficeBrain\Bundle\SearchBundle\Form\Type\ApiProductSearchType"
     *      },
     * )
	 * 
	 * @Method({"GET"})
	 * @Template()
	 *
	 */
	public function searchAction()
	{
		$data = null;
		$tmpData = parent::searchAction ();
		if (isset ( $tmpData ['search_result_array'] ) ) {
			$data = $tmpData ['search_result_array'];
			if (isset ( $data ['data'] ) && count ( $data ['data'] ) == 0) {
				$data ['data'] = null;
			}
		}
		
		$isError = 0;				
		if (count ( $data ) <= 0 ||  (isset ( $tmpData ['status'] ) && $tmpData ['status'] == 'error') ) {
			$isError = 1;
		}
		
		if ( ! $isError ) { 
			$data['data'] = $this->searchManager->getProductRowDataToShowMobileAPI($data['data'], $this->imageBaseUrl, $this->colorImageBaseUrl,$tmpData['attr_value_id']);
		}
		
		
		if ($isError) {
			return array(
                    'status' => self::ERROR,
                    'status_code' => self::ERROR_CODE,
                    'message' => isset($tmpData ['error_code'] )?$tmpData ['error_code'] :'No Record Found',
            );
		}
		
		return array(
				'status' => self::SUCCESS,
				'status_code' => self::SUCCESS_CODE,
				'response_data' => $data
		);
		
	}
	
	/**
	 *
	 * @author Employee Id: 4861
	 *
	 * Desciption: Perform search to find attribute list for given search criteria
	 *
	 * @param string search_query
	 *
	 * @return json Response
	 *
	 * @throws if result found return attribute list along with product count else null
	 *
	 * @Route("/search-attribute-filter-list", name="office_brain_search_bundle_search_attribute_filter_list_api")
	 *
	 * @ApiDoc(
     *      resource=true,
     *      section="Search",
     *      description="Get Product Filters .",
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      },
     *      requirements={     
     *             {"name"="_locale", "dataType"="string", "required"=true, "default"="en_us"},
     *             {"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *             {"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *             {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *             {"name"="main_filter", "dataType"="string","description"="set 'keyword' as default value"},
     *      	   {"name"="search_query","dataType"="string","description"="Search Keyword"}
     *      },
     *      input = {
     *      	"class" = "OfficeBrain\Bundle\SearchBundle\Form\Type\ApiProductSearchFilterType"
     *      },
     * )
	 * 
	 * @Method({"GET"})
	 * @Template()
	 *
	 */
	public function searchAttributeFilterListAction()
	{
		$data = parent::searchAttributeFilterListAction ();
		
		
		/* if (isset ( $data ['search_attribute_filter_array'] ['priceRange'] )) {
			foreach ( $data ['search_attribute_filter_array'] ['priceRange'] as $fieldName => $minmax ) {
				if ($minmax == null) {
					$data ['search_attribute_filter_array'] ['priceRange'] [$fieldName] = '';
				}
			}
		} */
		if (isset ( $data ['search_attribute_filter_array'] ['catalogYear'] ) ) {
			$data ['search_attribute_filter_array'] ['catalogYear'] = $this->setKeyValueArrayFormat($data ['search_attribute_filter_array'] ['catalogYear'],'year','count');
		}
		
		if (isset ( $data ['search_attribute_filter_array'] ['colorMapping'] ) ) {
			$data ['search_attribute_filter_array'] ['colorMapping']  = $this->setColorArrayWithImageUrl($data ['search_attribute_filter_array'] ['colorMapping'] );
		}
		
		if (isset ( $data ['search_attribute_filter_array'] ['priceCurrency'] ) ) {
			$data ['search_attribute_filter_array'] ['priceCurrency'] = $this->setPriceCurrencyFlagImage($data ['search_attribute_filter_array'] ['priceCurrency']);
		}	
		if (isset ( $data ['search_attribute_filter_array'] ['publicCustomTagText'] ) ) {
			$data ['search_attribute_filter_array'] ['publicCustomTagText'] = $this->getTagInArrayFormat($data ['search_attribute_filter_array'] ['publicCustomTagText']);
		}
		
		/* if (isset ( $data ['search_attribute_filter_array'] ['priceRange'] ) && count ( $data ['search_attribute_filter_array'] ['priceRange'] ) > 0) {
			foreach ( $data ['search_attribute_filter_array'] ['priceRange'] as $curKey => $curValue ) {
				if ($curValue == null) {
					$data ['search_attribute_filter_array'] ['priceRange'] [$curKey] = 0;
				}
			}
		} */			
		
		
		if ( $data ) {				
			return array (
					'status' => self::SUCCESS,
					'status_code' => self::SUCCESS_CODE,
					'data' => $data
			);
		}
		
		return array(
				'status' => self::ERROR,
				'status_code' => self::ERROR_CODE,
				'message' => 'No filter found',
		);
	}
	
	private function setPriceCurrencyFlagImage($priceCurrencyAry){
		$newPriceCurrencyAry = null;
		
		if(count( $priceCurrencyAry ) > 0 ){
			foreach ( $priceCurrencyAry as $curKey => $curValue ) {
				$tmpPriceCurrencyAry = $curValue;
				$imagePath = $this->getCurrencyFlagImagePath ( $curValue ['value'] );
				$tmpPriceCurrencyAry['image'] = $imagePath;
				$newPriceCurrencyAry[] = $tmpPriceCurrencyAry;
				unset($tmpPriceCurrencyAry);
			}
		}
		return $newPriceCurrencyAry;
	}
	
	private function setColorArrayWithImageUrl($colorAry){
		$newColorAry = null;
		if ( count( $colorAry ) > 0 ) {
			foreach ( $colorAry as $colorKey => $colorValue ) {
				$tmpColorValueAry = $colorValue;
				$imagePath = $this->colorImageBaseUrl. $colorValue ['master_id'] . '.jpg';
				$tmpColorValueAry['color_image'] = $imagePath;
				foreach ( $colorValue ['actual_color'] as $colorIKey => $colorIValue ) {
					$imagePath = $this->colorImageBaseUrl . $colorIValue ['actual_id'] . '.jpg';
					$tmpColorValueAry['actual_color'] [$colorIKey] ['color_image'] = $imagePath;
				}
				
				$newColorAry[] = $tmpColorValueAry;
			}
		}
		return $newColorAry;
	}
	
	private function setKeyValueArrayFormat($array,$keyVar='key',$valueVar='value'){
		$newAry = null;
		if ( count ( $array ) > 0 ) {
			$counter = 0;
			foreach ($array as $key => $value ) {
				$newAry [$counter] [$keyVar] = $key;
				$newAry [$counter] [$valueVar] = $value;
				$counter ++;
			}
		}
		return $newAry;
	}
	
	private function getTagInArrayFormat($tagString){
		$newCustomTagAry = null;
		
		if( count($tagString) > 0) {
		
			foreach ( $tagString as $tagKey => $tagCount ) {
				$tagAry = explode ( "|", $tagKey );
				$tagAry = array_map ( "trim", $tagAry );
				$newCustomTagAry [] = array (
						'id' => (isset ( $tagAry [0] ) ? $tagAry [0] : null),
						'name' => (isset ( $tagAry [1] ) ? $tagAry [1] : null),
						'color_hex' => (isset ( $tagAry [2] ) ? $tagAry [2] : null),
						'featured_icon' => (isset ( $tagAry [3] ) ? $tagAry [3] : null),
						'class' => (isset ( $tagAry [4] ) ? $tagAry [4] : null),
						'slug' => (isset ( $tagAry [5] ) ? $tagAry [5] : null),
						'tag_icon' => (isset ( $tagAry [6] ) ? $tagAry [6] : null),
						'tag_type' => (isset ( $tagAry [7] ) ? $tagAry [7] : null),
						'count' => $tagCount
				);
			}
		}
		return $newCustomTagAry;
	}
	
 	private function getCurrencyFlagImagePath($currency) {
 		$currency = strtolower ( $currency );
 		return $this->baseURL . '/bundles/'. strtolower(str_replace('ThemeBundle','Theme',$this->projectSetting ['instance_theme_path'])) .'/' . $this->projectSetting ['instance_theme'] . '/images/' . $currency . '-currency-icon.png';
 	}
	
}