import groovy.util.Node

import java.util.List

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

/**
 * Content URL extractor plugin for Yahoo movies
 * 
 * http://movies.yahoo.com/rss
 * 
 * @author Petr Nejedly
 *
 */
class YahooMovies extends FeedItemUrlExtractor {
    
    final VALID_FEED_URL = '^http(s)*://.*\\.yahoo\\.com/movies/.*$'
   
    String getExtractorName() {
        return 'Yahoo Movies'
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
    
    ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
        def linkUrl = links.default
        def contentUrl
        def thumbnailUrl
		
		def matcher = linkUrl =~ '^.+/(\\d+)/info$'
		assert matcher != null
		assert matcher.hasGroup()

		def videoId = matcher[0][1]
		//log(videoId)
		
		String trailerInfoPage = new URL("http://movies.yahoo.com/movie/${videoId}/trailer").getText()
		if(trailerInfoPage != null) {			
			def contentIdMatcher = trailerInfoPage =~ 'var clipId=(\\d+);'
			assert contentIdMatcher != null
			if(contentIdMatcher.count > 0) {
				def contentId = contentIdMatcher[0][1]
				Integer randomToken = NumberUtils.getRandomInInterval(100000000, 999999999)
				String contentInfoUrl = "http://cosmos.bcst.yahoo.com/rest/v2/pops;dynamicstream=1;tech=flv,mp4;id=${contentId};element=stream;lmsoverride=1;outputformat=mrss;lg=${randomToken}"
				String contentInfoXml = new URL(contentInfoUrl).getText()
				//log(contentInfoXml)
				contentInfoXml = contentInfoXml.replaceAll ('&', '&amp;')
				def contentInfoNode = new XmlParser().parseText( contentInfoXml )
				List contentNodes = contentInfoNode.channel.item.'media:group'.'media:content'
				List sortedContentNodes = contentNodes.sort { it.'@bitrate'.toInteger() }
				Node selectedMediaItem = findSuitableItem(sortedContentNodes, requestedQuality)
				contentUrl = "${selectedMediaItem.'@url'} playpath=${selectedMediaItem.'@path'}"
				return new ContentURLContainer(contentUrl: contentUrl)
			} else {
				log('Cannot find clipId, it\'s likely there is no video content for the movie feed')
				return null
			}
		}
		
		log('Could not find content URL')
		return null;
    }
	
	def Node findSuitableItem(List items, PreferredQuality requestedQuality) {
		if(requestedQuality == PreferredQuality.LOW) {
			// worst quality, get the first from the list
			return items.head()
		} else if (requestedQuality == PreferredQuality.MEDIUM) {
			// get item from the middle
			return items.get(Math.floor(items.size()/2).toInteger())
		} else {
			// best quality, take the last url
			return items.last()
		}
	}
	
    static void main(args) {
		// this is just to test
        YahooMovies extractor = new YahooMovies()
		
		assert extractor.extractorMatches( new URL("http://rss.ent.yahoo.com/movies/thisweek.xml") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		
        Map videoLinks = ['default': new URL('http://us.rd.yahoo.com/movies/top/opening/batmanyearone2011/?http://movies.yahoo.com/movie/1810198479/info')] 
        ContentURLContainer result = extractor.extractUrl(videoLinks, PreferredQuality.MEDIUM)		
        println "Result: $result"		 
    }
}