<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Youtube_model {
	private $yt_api_key;
	const REDIS_HOST = "127.0.0.1";
	const REDIS_PORT_WRITE = "22130";
	const REDIS_PORT_READ = "22130";
	const TTL = 60 * 30;
	const REDIS_KEY_PREFIX = "cms_";
	
    function __construct()
    {
        // parent::__construct();
		// $this->yt_api_key='AIzaSyBDSr86uNAYoqRpVHODEPzWVY1F-21ikwo';
		// $this->yt_api_key='AIzaSyDZWsGkdPYkDhZ6K7d5S-HTSK06gJrHomY';
		// $this->yt_api_key='AIzaSyClapC08WXxLTW-TwlUSfpBuC5s6Y5YpJw';
		$this->yt_list_api_key='AIzaSyAlmrG48DzU8p_A70narXZJRFreyF25aLQ';
		$this->yt_search_api_key='AIzaSyC02tdorhXbZIFEQfbC30_DF-Ti9XCPMoc';
		// $this->yt_search_api_key='AIzaSyDygN6B2LM-FOcG2iLGuw3g0mWXRDK338E';
		$this->_redis = new Redis();

    }
	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 getYoutubeVideo($search='')
	{
		
		if( $search != '' ) {
			$feedUrl = 'https://www.googleapis.com/youtube/v3/search?maxResults=25&part=snippet&key='. $this->yt_search_api_key .'&type=video&q='.urlencode($search);
			// $ttl = 60 * 60 * 2; // 2 hours
		} else {
			$feedUrl = 'https://www.googleapis.com/youtube/v3/videos?chart=mostPopular&key='. $this->yt_list_api_key .'&part=snippet&type=video&maxResults=25';	
			// $ttl = 60 * 30 ; // 30 min
		}
		$ttl = 60 * 60 * 2; // 2 hours
		$key = md5('youtube_'.$feedUrl);		
		$result = $this->getRedisKeyData($key);

		if( empty( $result ) || $result == '') {

			$feed = new DomDocument();	

			$result = array();
			$params = array( );		
			
			$ch = curl_init( $feedUrl. "?" . http_build_query( $params ) );
			curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
			$output = curl_exec( $ch );
			curl_close( $ch );
			$decoded_data = json_decode( $output, true );
			foreach( $decoded_data['items'] as $item ) {

				$Thumbnail = $item['snippet']['thumbnails']['default']['url'];
				$Title =  $item['snippet']['title'];
				$Description = $item['snippet']['description'];
				if($search != '') {
					$Link = $item['id']['videoId'];
				} else {
					$Link = $item['id'];
				}
				
				// $ID =  str_replace('http://gdata.youtube.com/feeds/api/videos/', '' ,$Link);
				array_push($result,
					array('Thumbnail' => $Thumbnail,
						'Title' => $Title,
						'Description' => $Description,
						'Link' => $Link,
						'ID' => str_replace('http://gdata.youtube.com/feeds/api/videos/', '' ,$Link)
					)		
				);
			}

			if( !empty( $result ) ) {
				$this->setRedisKeyData($key, $result);
			}
			
		} 	
		return $result;
	}
}
