<?php

class RedisLib
{

    const REDIS_KEY_PREFIX = 'cp_';
    
    const WRITE_REDIS_HOST = "127.0.0.1";
	const WRITE_REDIS_PORT = "22133";
    const READ_REDIS_HOST = "127.0.0.1";
	const READ_REDIS_PORT = "22134";
    const TTL = 60 * 60 * 24;
    public $_read_redis;
    public $_write_redis;

    function __construct()
    {
        $this->_write_redis = new Redis();
        $this->_write_redis->pconnect(self::WRITE_REDIS_HOST, self::WRITE_REDIS_PORT);
    }

    public function setRedisKeyData($key, $data)
    {
        try {
            return $this->_write_redis->set($key, json_encode($data), self::TTL);
        } catch (Exception $e) {
            // var_dump($e->getMessage());
        }
    }

    public function setRedisHashKeyData($hash, $key, $data)
    {
        try {
            $result = $this->_write_redis->hSet($hash, $key, json_encode($data));
        } catch (Exception $e) {
            // var_dump($e->getMessage());
        }
    }

    public function getRedisKeyData($key)
    {
        try {
            $this->_read_redis = new Redis();
            $this->_read_redis->pconnect(self::READ_REDIS_HOST, self::READ_REDIS_PORT);
            return json_decode($this->_read_redis->get($key), true);
        } catch (Exception $e) {
            var_dump($e->getMessage());
        }
    }

    public function deleteRedisData($hash, $key)
    {
        try {
            return $this->_write_redis->hDel($hash, $key);
        } catch (Exception $e) {
            var_dump($e->getMessage());
        }
    }

    public function get_hash_data($key, $cat_id) {
		try{
            $this->_read_redis = new Redis();
            $this->_read_redis->pconnect(self::READ_REDIS_HOST, self::READ_REDIS_PORT);
			$result = $this->_read_redis->hget( $key, $cat_id) ;
			$result = json_decode($result, true);
		} catch (\Exception $ex) {
			var_dump($ex->getMessage());
		}
		return $result;
	}

    public function get_key_data($key) {
		try{
            $this->_read_redis = new Redis();
            $this->_read_redis->pconnect(self::READ_REDIS_HOST, self::READ_REDIS_PORT);
			$result = $this->_read_redis->get( $key) ;
			$result = json_decode($result, true);
		} catch (\Exception $ex) {
			var_dump($ex->getMessage());
		}
		return $result;
	}
    
    public function searchInRedis( $keyword ) {
        $this->_read_redis = new Redis();
        $this->_read_redis->pconnect(self::READ_REDIS_HOST, self::READ_REDIS_PORT);
        $keyword = strtolower( $keyword );
        
        $result = [];
        $it = 100;
        $this->_read_redis->setOption( Redis::OPT_SCAN, Redis::SCAN_RETRY ); /* don't return empty results until we're done */
        while( $arr_mems = $this->_read_redis->hScan( 'cp_brands', $it, "$keyword*" ) ) {
            $result = array_merge( $result, $arr_mems );
            if( count($result) >= 10000 ) {
                break;
            }
        }
        return $result;
    }
}
