<?php 
/**
 * Common Library for Shopping Guide of amazon_feed (DES-1344)
 */

class AmazonFeed {
	const REDIS_HOST = '127.0.0.1';
	const REDIS_PORT = '22130'; 

	const SPHINX_IP = '127.0.0.1';
	const SPHINX_HOST= '22139';

	const REDIS_KEY_CATEGORY_SUBCATEGORY_META = 'amazon_feed_category_subcategory_prod_counts';
	const REDIS_KEY_PROMOTED_PRODUCTS = 'amazon_feed_promoted_products';
	const KEY_TTL = 86400; // 1 day

	const SPHINX_INDEX = 'amazon_feed_new';
	const RANGESIZE = 35000;   // size of each slot
	const MAXPRICE = 40000;   // maximum price before reset

	private $_sphinx;
	private $_redis = null;

	public function __construct() {
		$this->_redis = new Redis();
		$this->_redis->connect( self::REDIS_HOST, self::REDIS_PORT );
		$this->_sphinx =  new PDO('mysql:host='.self::SPHINX_IP.';port='.self::SPHINX_HOST.';', '', '',array(PDO::ATTR_PERSISTENT => TRUE));
	}

	public function getArray($query) {
		try{
			$result = false;
			$sphinxQuery = $this->_sphinx->query($query);
			//var_dump($this->Conn->errorInfo());
			if (is_object($sphinxQuery)) {
				$result = $sphinxQuery->fetchAll(PDO::FETCH_ASSOC);
			}

		} catch (\Exception $ex) {
			//var_dump($ex->getMessage());
			return false;
		}
		return $result;
	}

	private function getCatSubcategoryInfo() {
		$data = $this->getArray("select master_category, category, count(*) as cnt from ".self::SPHINX_INDEX." group by master_category, category");
		$cat_subcat_info = array();
		if (!empty($data)){
			foreach ($data as $row) {
				$cat_subcat_info[$row['master_category']][$row['category']] = $row['cnt'];
			}
			return $cat_subcat_info;
		} else {
			return false;
		}
	}

	private function pushCatgeoryInfoRedis($site_id, $category_subcategory) {
		if (isset($category_subcategory) && count($category_subcategory)) {
			foreach ($category_subcategory as $category => $info) {
				$category = str_replace([' ', '&'] , ['-sp-', '-and-'], $category);
				$this->_redis->hset(self::REDIS_KEY_CATEGORY_SUBCATEGORY_META, $category, json_encode($info));
			}
			$this->_redis->EXPIRE(self::REDIS_KEY_CATEGORY_SUBCATEGORY_META, self::KEY_TTL);
		}
	}

	public function get_all_hash_data($key) {
		try{
			$result = $this->_redis->hgetall( $key) ;
		} catch (\Exception $ex) {
			//var_dump($ex->getMessage());
			return false;
		}
		return $result;
	}

	private function getAndPushCategorySubCategoryIntoRedis($site_id) {
		$get_cat_sub_cat = $this->getCatSubcategoryInfo($site_id);
		$this->pushCatgeoryInfoRedis($site_id, $get_cat_sub_cat);
	}

	public function getCategorySubCategoryInfo($site_id = null) {
		$result = $this->get_all_hash_data(self::REDIS_KEY_CATEGORY_SUBCATEGORY_META);
		if (!$result) {
			$this->getAndPushCategorySubCategoryIntoRedis($site_id);
			$result = $this->get_all_hash_data(self::REDIS_KEY_CATEGORY_SUBCATEGORY_META);
		}
		return $result;
	}

	private function getAndSetPromotedProducts($site_id) {
		$hour = date('G'); // 24-hour format of an hour without leading zeros (0 through 23)
		// cycle the start price after reaching max
		$start = ($hour * self::RANGESIZE) % self::MAXPRICE + 1;
		$end   = $start + self::RANGESIZE - 1;
		return $this->getArray("select * from ".self::SPHINX_INDEX."  order by rand() limit 10");
	}

	public function getPromotedProducts($site_id = null) {
		$result = $this->_redis->get(self::REDIS_KEY_PROMOTED_PRODUCTS);
		if (!$result) {
			$result = $this->getAndSetPromotedProducts($site_id);
			$this->_redis->set(self::REDIS_KEY_PROMOTED_PRODUCTS, json_encode($result));
			$this->_redis->EXPIRE(self::REDIS_KEY_PROMOTED_PRODUCTS, 60*60);
		} else {
			$result = json_decode($result, 1);
		}
		return $result;
	}

}

?>
