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

/**
 * GameTrailers.com content URL extractor plugin. 
 * 
 * List of feeds: http://www.gametrailers.com/about/rss/
 * 
 * Based on: https://code.google.com/p/dandar3-xbmc-addons/source/browse/trunk/addons/plugin.video.gametrailers/resources/lib/gametrailers_play.py
 *  
 * @author Petr Nejedly
 *
 */
class GameTrailers extends FeedItemUrlExtractor {
    
    final VALID_FEED_URL = '^http(s)*://www\\.gametrailers\\.com/.*/feed$'
    
    String getExtractorName() {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
	
	int getVersion() {
		return 2
	}
    
    ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
        def linkUrl = links.default
        		
		String html = linkUrl.getText()
		def matcher = html =~ "(?s)data-contentId='(.+?)'"
		assert matcher != null
		assert matcher.size() > 0 : "Missing data-contentId"

		def dataContentId = matcher[0][1]
		def mediaFeedNode = new XmlParser().parse( "http://www.gametrailers.com/feeds/mrss/?uri=${dataContentId}" )
		def itemId = mediaFeedNode.channel.item[0].'media:group'.'media:category'.find { it -> it.'@scheme' == 'urn:mtvn:id'}.text()
		def thumbnailUrl = mediaFeedNode.channel.item[0].'media:group'.'media:thumbnail'.'@url'.text()
		def rendition = requestedQuality in [PreferredQuality.MEDIUM, PreferredQuality.LOW] ? "sd" : "hd"
		def mediaItemNode = new XmlParser().parse( "http://www.gametrailers.com/feeds/mediagen/?uri=${itemId}&forceProgressive=true&renditionSize=${rendition}" )
		def contentUrl = mediaItemNode.video.item[0].rendition[0].src[0].text()
		
        return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: contentUrl, thumbnailUrl: thumbnailUrl)
    }
    
    static void main(args) {
		// this is just to test
        GameTrailers extractor = new GameTrailers()
		
		assert extractor.extractorMatches( new URL("http://www.gametrailers.com/videos-trailers/feed") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		
        Map links = ['default': new URL('http://www.gametrailers.com/videos/0wo5s1/neverwinter-mounts-trailer')] 
        ContentURLContainer result = extractor.extractUrl(links, PreferredQuality.HIGH)
        println "Result: $result"
    }
}