<?php
require_once MVROOT."/aggregation_service/feeds/BaseFeed.class.php";

class YouTubeFeed extends BaseFeed {

	function __construct() {
		parent::__construct('JSON');
	}
	
	public function request($username) {
		$t='$t';
		
		$data = parent::request("http://gdata.youtube.com/feeds/api/users/${username}?v=2&alt=json");
		$location = (array)$data->entry;
		$location = $location['yt$location']->$t;
		
		$data = parent::request("http://gdata.youtube.com/feeds/api/users/${username}/uploads?alt=json");
		$data=$data->feed->entry;
		
		foreach($data as $item) {
			$item=(array)$item;
			if(!isset($item['id'])) continue;
			
			$id=explode('/',$item['id']->$t);
			$id=$id[sizeof($id)-1];
			
			parent::import(array(
				'contentType'=>'video',
				'source'=>'youtube',
				'source_id'=>$id,
				'url'=>$id,
				'title'=>$item['title']->$t,
				'thumbnail'=>"http://i3.ytimg.com/vi/$id/default.jpg",
				'thumbnail_hq'=>"http://i4.ytimg.com/vi/$id/hqdefault.jpg",
				'description'=>$item['content']->$t,
				'created'=>strtotime($item['published']->$t),
				'date'=>date('M j, Y, g:i a', strtotime($item['published']->$t)),
				'tags'=>$this->getTags($item),
				'views'=>$item['yt$statistics']->viewCount,
				'location'=>$location,
			));
		}
		
		$playlists=parent::request("https://gdata.youtube.com/feeds/api/users/${username}/playlists?v=2&alt=json");
		$playlists=$playlists->feed->entry;
		if(!isset($playlists)) return;
		
		foreach($playlists as $item) {
			$item=(array)$item;
			if(!isset($item['id'])) continue;
			
			$t='$t';
			$id=explode(':',$item['id']->$t);
			$id=$id[sizeof($id)-1];
			
			$playlist=parent::request("http://gdata.youtube.com/feeds/api/playlists/${id}?v=2&alt=json");
			$playlist=$playlist->feed->entry;
			if(!isset($playlist)) continue;
			
			foreach($playlist as $item0) {
				$item0=(array)$item0;
				if(!isset($item0['id'])) continue;
				
				$id='yt$videoid';
				$title='media$title';
				$published='yt$uploaded';
				$content='media$description';
				
				$id=$item0['media$group']->$id->$t;
				$title=$item0['media$group']->$title->$t;
				$published=$item0['media$group']->$published->$t;
				$content=$item0['media$group']->$content->$t;
				$views=$item0['yt$statistics']->viewCount;
				
				parent::import(array(
					'contentType'=>'video',
					'source'=>'youtube',
					'source_id'=>$id,
					'url'=>$id,
					'title'=>$title,
					'thumbnail'=>"http://i3.ytimg.com/vi/$id/default.jpg",
					'thumbnail_hq'=>"http://i4.ytimg.com/vi/$id/hqdefault.jpg",
					'description'=>$content,
					'created'=>strtotime($published),
					'date'=>date('M j, Y, g:i a', strtotime($published)),
					'tags'=>$this->getTags($item0),
					'views'=>$views,
					'location'=>$location,
				));
			}
		}
	}
	
	private function getTags($item) {
		$cat=array();
		if(isset($item['category'])) {
			array_shift($item['category']);
			foreach($item['category'] as $c) $cat[]=$c->term;
		}
		return $cat;// implode(',',$cat);
	}
	
}

?>