
import org.serviio.library.metadata.*
import org.serviio.library.online.*
import org.serviio.util.*

/**
 * Content URL extractor plugin for Gamespot video feeds.
 *
 * Based on http://forum.xbmc.org/showthread.php?t=47393
 * 
 * @author Petr Nejedly
 *
 */
class Gamespot extends FeedItemUrlExtractor {
	
	final VALID_FEED_URL = '^(?:https?://)?.*?gamespot\\.com/rss/.*$'
	
	String getExtractorName() {
		return 'Gamespot'
	}
	
	boolean extractorMatches(URL feedUrl) {
		return feedUrl ==~ VALID_FEED_URL
	}
	
	int getVersion() {
		return 2
	}
	
	ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
		def linkUrl = links.default
		def contentUrl
		
		def matcher = linkUrl =~ '(\\d+)/?$'
		assert matcher != null
		assert matcher.hasGroup()
		
		def videoId = matcher[0][1]
		
		URL playerXmlUrl = new URL("http://www.gamespot.com/pages/video_player/xml.php?id=$videoId")
		String playerXml = openURL(playerXmlUrl,'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7')
		def playerNode = new XmlParser().parseText(playerXml)
		def clipNode = playerNode.playList.clip
		List videoClips = clipNode.httpURI.videoFile.findAll { it }
		String captureUrl = clipNode.screenGrabURI.text()
		String thumbnailUrl = captureUrl.replaceFirst('_(\\d)+\\.', '_140.')		
		contentUrl = findSuitableQuality(videoClips, requestedQuality)
		return new ContentURLContainer(contentUrl: contentUrl, thumbnailUrl : thumbnailUrl)
	}
	
	def String findSuitableQuality(List videoClips, PreferredQuality requestedQuality) {
		List sortedClips = videoClips.sort { it.rate.text().toInteger() }
		def selectedClip
		if(requestedQuality == PreferredQuality.LOW || sortedClips.size() <= 1) {
			// worst quality, get the first from the list
			selectedClip =sortedClips.head()
		} else if (requestedQuality == PreferredQuality.MEDIUM) {
			// get item from the middle
			selectedClip = sortedClips.get(Math.round(sortedClips.size()/2).toInteger())
		} else {
			// best quality, take the last url
			selectedClip = sortedClips.last()
		}
		return selectedClip.filePath.text()
	}
	
	static void main(args) {
		// this is just to test
		Gamespot extractor = new Gamespot()
		
		assert extractor.extractorMatches( new URL("http://uk.gamespot.com/rss/game_updates.php?platform=5&type=14") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		
		Map videoLinks = ['default': new URL('http://uk.gamespot.com/tomb-raider/videos/tomb-raider-alternative-reborn-trailer-6404675/')]
		ContentURLContainer result = extractor.extractUrl(videoLinks, PreferredQuality.HIGH)
		println "Result: $result"		 
	}
}