<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Rssengine_model {
	const REDIS_HOST = "127.0.0.1";
	const REDIS_PORT_WRITE = "22130";
	const REDIS_PORT_READ = "22130";
	
	const TTL = 60 * 30;
    function __construct()
    {
		$this->_redis = new Redis();
		$this->db = CommonPDOConnector::connect('MasterLP');
    }
	public function getRedisKeyData($key)
	{
		try {
			$this->_redis->pconnect(self::REDIS_HOST, self::REDIS_PORT_READ);
			return json_decode($this->_redis->get($key), true);
		} catch (Exception $e) {
			var_dump($e->getMessage());
		}
	}
	public function setRedisKeyData($key, $data)
	{
		try {
			$this->_redis->pconnect(self::REDIS_HOST, self::REDIS_PORT_WRITE);
			return $this->_redis->set($key, json_encode($data), self::TTL);
		} catch (Exception $e) {
			var_dump($e->getMessage());
		}
	}
	public function getRSSArticles($category = null, $keyword = null, $limit = 10) {
		$key = md5('rssengine_'.$category.$keyword.$limit);
		$ttl = 60 * 60 * 1; // 1 hour
		
		$results = $this->getRedisKeyData($key);
		
		if(!$results) {
			if($category !== null) {
				$query = $this->db->query("select id, title, description, link, source, date from rss_article where category = '$category' order by date desc limit $limit;");
			} else if($keyword !== null) {
				$query = $this->db->query("select id, title, description, link, source, date from rss_article where title like '%".strtolower($keyword)."%' order by date desc limit $limit;");
			}
			$results = $query->fetchAll(PDO::FETCH_ASSOC);
			if (count($results) > 0) {
				$this->setRedisKeyData($key, $results);
			}
		}
		
		return $results;
	}
	public function getAllRSSArticles($limit = 10) {
		$key = md5('rssengine_all'.$limit);
		$ttl = 60 * 60 * 1; // 1 hour
		
		$results = $this->getRedisKeyData($key);
		
		if(!$results) {
			$query = $this->db->query("select id, title, description, link, source, date from rss_article order by date desc limit $limit;");
			$results = $query->fetchAll(PDO::FETCH_ASSOC);
			if (count($results) > 0) {
				$this->setRedisKeyData($key, $results);
			}
		}
		
		return $results;
	}
	
	public function getRSSArticleDetail($id) {
		$query = $this->db->query("select id, title, description, link, source, date from rss_article where id = '$id';");

		$results = $query->fetchAll(PDO::FETCH_ASSOC);
		
		return $results;
	}
}
