<?php  

class mCachedb extends Memcache {
		static private $instance = null;
		static private $port = 11211;
		static function mGet() {
			if (self::$instance == null) {
				self::$instance = new Memcache;
				self::$instance->addServer("127.0.0.1", self::$port);
			}
			return self::$instance;
		}
}

class Anyclip_model{
	
	var $_clientid = '462DE31E';
	var $_appkey = 'C6092F30-5147-4E48-B3A5-A53505570981';


	public function shuffle_assoc($list) { 
		if (!is_array($list)) return $list; 

		$keys = array_keys($list); 
		shuffle($keys); 
		$random = array(); 
		foreach ($keys as $key) 
			$random[$key] = $list[$key]; 

		return $random; 
	}

	public function getAnyclipVideo($search, $num = 3)
	{
		$videos = array();

		$count = 0;

		$mkey = md5("coloVideos");
		$expire = 900;
		$videosArr = array();

		if(!$videosArr = mCachedb::mGet()->get($mkey)) {
			include_once("lib/php/include/db.php");
			$db = ConnectToRead();

			$sql = "select * from rep_videos";
			$res = mysql_query($sql, $db);
			while($row = mysql_fetch_assoc($res))
			{
				$title = trim($row['title']);
				$desc = trim($row['description']);
				$id = $row['id'];

				if($id < 10)
					$vidId = "00".$id;
				else if($id >= 10 && $id < 100)
					$vidId = "0".$id;
				else
					$vidId = $id;

				$thumb = "http://b36df47b3d.site.internapcdn.net/video/".$vidId.".jpeg";
				$videosArr[$id] = array($title, $desc, $thumb);
			}
		
			mCachedb::mGet()->set($mkey, $videosArr, 0, $expire);
		}
		
		$videosArr = $this->shuffle_assoc($videosArr);
		foreach($videosArr as $vid=>$vArr)
		{
			if($count < $num)
			{
				if($vid < 10)
					$vidId = "00".$vid;
				else if($vid >= 10 && $vid < 100)
					$vidId = "0".$vid;
				else
					$vidId = $vid;
				
				array_push($videos,
					array('Thumbnail' => $vArr[2],
						'Title' => $vArr[0],
						'Description' => $vArr[1],
						'ID' => $vidId
					)
				);
				$count++;
			}
			else
				break;
		}
		return $videos;

		$vidArr = range(1, 38);
		shuffle($vidArr);
	
		for($i = 0; $i < $num; $i++)
		{
			$vidNum = $vidArr[$i];
			if($vidNum < 10)
				$vidId = "00".$vidNum;
			else
				$vidId = "0".$vidNum;

			$thumb = "http://b36df47b3d.site.internapcdn.net/video/".$vidId.".jpeg";
			array_push($videos,
					array('Thumbnail' => $thumb,
						'Title' => "",
						'Description' => "",
						'ID' => $vidId
					)
			);
		}
		return $videos;

		//return $this->botr_model->getBotrVideo($search, $num);
		
		$this->benchmark->mark('anyclip_start');
		/*
		$key = md5($search);
		$ttl = 60 * 60 * 24 * 30; // 30 days
		
		$videos = $this->cache->get($key);
		
		if($videos === false || count($videos) == 0) {
			
			include(APPPATH.'libraries/Vimeo.php');
			
			$vimeo = new phpVimeo('8376aae43c6b11db0caa2e7a12428b058d0e587b', '801d76dc123e8d67d57b77ae10a4e7ae7f2909b6');
			$vimeos = $vimeo->call('vimeo.videos.search', array('full_response' => true, 'query' => $search, 'per_page' => 50));
			$videos = array();
			
			foreach($vimeos->videos->video as $video) {
				if($video->embed_privacy == 'anywhere') {
					array_push($videos,
						array('Thumbnail' => $video->thumbnails->thumbnail[0]->_content,
							'Title' => $video->title,
							'Description' => $video->description,
							'ID' => $video->id
						)
					);
				}
			}
			
			if(count($videos) > 0) {
				$this->cache->save($key, $videos, $ttl);
			}
		}
		$this->benchmark->mark('anyclip_end');
		return array_slice($videos, 0, $num);
		*/
		$feed = new DomDocument();
		$params = '/api/search/?cf=1&cff=707272&cid='.$this->_clientid.'&efilter=64&maxResults='.$num.'&q='.rawurlencode($search).'&scenesFirst=true&startIndex=0';
		$sig = sha1('/api/search/?appKey='.$this->_appkey.'&cf=1&cff=707272&cid='.$this->_clientid.'&efilter=64&maxResults='.$num.'&q='.$search.'&scenesFirst=true&startIndex=0');
		$feedUrl = 'http://apis.anyclip.com'.$params.'&sig='.$sig;
		$videos = array();
		
		$this->curl->create($feedUrl);
		$this->curl->option(CURLOPT_TIMEOUT, 2);
		$data = $this->curl->execute();
		
		if($data) {
			$feed->loadXML($data);
			####### PARSING XML ####
			foreach($feed->getElementsByTagName('result') as $video) {
				$thumb = $video->getElementsByTagName('thumbnail')->item(0)->firstChild->nodeValue;
				$title = $video->getElementsByTagName('title')->item(0);
				$title = $title->getElementsByTagName('name')->item(1)->firstChild->nodeValue;
				if($title == null) {
					$title = $video->getElementsByTagName('title')->item(0);
					$title = $title->getElementsByTagName('name')->item(0)->firstChild->nodeValue;
				}
				$desc = $video->getElementsByTagName('name')->item(0)->firstChild->nodeValue;
				$id = $video->getElementsByTagName('code')->item(0)->firstChild->nodeValue;
				
				array_push($videos,
					array('Thumbnail' => $thumb,
						'Title' => $title,
						'Description' => $desc,
						'ID' => $id
					)
				);
			}
			
			$this->benchmark->mark('anyclip_end');
			return array_slice($videos, 0, $num);
		} else {
			
			$this->benchmark->mark('anyclip_end');
			return array();
		}
	}
}