<?php

class EWRmedio_Services_YouTube extends XenForo_Model
{
	public static function dumpMedia($service, $matches)
	{
		$client = new Zend_Http_Client('https://www.googleapis.com/youtube/v3/videos');
		$client->setParameterGet(array(
			'part' => 'snippet,contentDetails,status',
			'id' => $matches['sval1'],
			'key' => $service['service_apikey'],
		));
		$feed = $client->request()->getBody();
		$json = json_decode($feed, true);
		
		if (!empty($json['error']))
		{
			throw new XenForo_Exception($json['error']['message'].': '.$json['error']['errors'][0]['reason'], true);
		}
	
		if (empty($json['items']))
		{
			throw new XenForo_Exception(new XenForo_Phrase('media_url_did_not_retrieve_valid_data'), true);
		}
		
		$json = $json['items'][0];
		
		if ($json['status']['uploadStatus'] != 'processed' || $json['status']['privacyStatus'] == 'private' || !$json['status']['embeddable'])
		{
			throw new XenForo_Exception(new XenForo_Phrase('media_url_not_available'), true);
		}
		
		preg_match('#PT(?<h>\d+H)?(?<m>\d+M)?(?<s>\d+S)?#i', $json['contentDetails']['duration'], $duration);
		
		$json['duration'] = 0;
		if (!empty($duration['s'])) { $json['duration'] += $duration['s']; }
		if (!empty($duration['m'])) { $json['duration'] += $duration['m'] * 60; }
		if (!empty($duration['h'])) { $json['duration'] += $duration['h'] * 60 * 60; }
		
		$thumb = end($json['snippet']['thumbnails']);
	
		$media = array(
			'media_value1' => $matches['sval1'],
			'media_value2' => '',
			'media_thumb' => $thumb['url'],
			'media_title' => $json['snippet']['title'],
			'media_description' => $json['snippet']['description'],
			'media_duration' => $json['duration'],
			'media_keywords' => null,
		);
		
		return $media;
	}
	
	public static function dumpPlaylist($service, $matches, $params)
	{
		$mediaModel = XenForo_Model::create('EWRmedio_Model_Media');
		$medias = array();
		$nextPage = '';
	
		do
		{
			$client = new Zend_Http_Client('https://www.googleapis.com/youtube/v3/playlistItems');
			$client->setParameterGet(array(
				'part' => 'contentDetails',
				'playlistId' => $matches['sval1'],
				'maxResults' => 5,
				'pageToken' => $nextPage,
				'key' => $service['service_apikey'],
			));
			$feed = $client->request()->getBody();
			$json = json_decode($feed, true);
			
			if (!empty($json['error']))
			{
				throw new XenForo_Exception($json['error']['message'].': '.$json['error']['errors'][0]['reason'], true);
			}
	
			if (empty($json['items']))
			{
				throw new XenForo_Exception(new XenForo_Phrase('media_url_did_not_retrieve_valid_data'), true);
			}
			
			$nextPage = !empty($json['nextPageToken']) ? $json['nextPageToken'] : '';
			
			$mediaIDs = array();
			
			foreach ($json['items'] AS $media)
			{
				$mediaIDs[] = $media['contentDetails']['videoId'];
			}
		
			$client = new Zend_Http_Client('https://www.googleapis.com/youtube/v3/videos');
			$client->setParameterGet(array(
				'part' => 'snippet,contentDetails,status',
				'id' => implode(',', $mediaIDs),
				'key' => $service['service_apikey'],
			));
			$feed = $client->request()->getBody();
			$json2 = json_decode($feed, true);
		
			if (!empty($json2['error']))
			{
				throw new XenForo_Exception($json2['error']['message'].': '.$json2['error']['errors'][0]['reason'], true);
			}
			
			if (empty($json2['items']))
			{
				throw new XenForo_Exception(new XenForo_Phrase('media_url_did_not_retrieve_valid_data'), true);
			}
			
			foreach ($json2['items'] AS $entry)
			{
				if ($entry['status']['uploadStatus'] != 'processed' || $entry['status']['privacyStatus'] == 'private' || !$entry['status']['embeddable'])
				{
					continue;
				}
		
				preg_match('#PT(?<h>\d+H)?(?<m>\d+M)?(?<s>\d+S)?#i', $entry['contentDetails']['duration'], $duration);
		
				$entry['duration'] = 0;
				if (!empty($duration['s'])) { $entry['duration'] += $duration['s']; }
				if (!empty($duration['m'])) { $entry['duration'] += $duration['m'] * 60; }
				if (!empty($duration['h'])) { $entry['duration'] += $duration['h'] * 60 * 60; }
				
				$thumb = end($entry['snippet']['thumbnails']);
		
				$medias[] = array(
					'media_value1' => $entry['id'],
					'media_value2' => '',
					'media_thumb' => $thumb['url'],
					'media_title' => $entry['snippet']['title'],
					'media_description' => $entry['snippet']['description'],
					'media_duration' => $entry['duration'],
					'media_keywords' => null,
					'exists' => $mediaModel->getMediaByServiceInfo($service['service_id'], $entry['id'], ''),
				);
			}
		} while ($nextPage);
	
		if (empty($medias))
		{
			throw new XenForo_Exception(new XenForo_Phrase('media_url_did_not_retrieve_valid_data'), true);
		}
	
		return array($medias, $params);
	}
}