import org.serviio.library.metadata.*
import org.serviio.library.online.*

/**
 * YouTube.com content URL extractor plugin. 
 * 
 * Based on youtube_dl Python script (http://rg3.github.com/youtube-dl/)
 * 
 * @see http://en.wikipedia.org/wiki/Youtube#Quality_and_codecs
 *  
 * @author Petr Nejedly
 *
 */
class YouTube extends FeedItemUrlExtractor {

    final VALID_PLAYER_URL = '^((?:https?://)?(?:youtu\\.be/|(?:\\w+\\.)?youtube(?:-nocookie)?\\.com/)(?:(?:(?:v|embed|e)/)|(?:(?:watch(?:_popup)?(?:\\.php)?)?(?:\\?|#!?)(?:.+&)?v=)))?([0-9A-Za-z_-]+)(.+)?$'
    final VALID_FEED_URL = '^http(s)*://.*youtube\\..*$'
	/* Listed in order of quality */
    final availableFormats = ['37', '46', '22', '45', '35', '34', '18', '44', '43', '6', '5']
    
    String getExtractorName() {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
    
    ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
        def linkUrl = links.alternate != null ? links.alternate : links.default
        def contentUrl
        def thumbnailUrl
		def expiryDate
		def expiresImmediately
		def cacheKey
		
        def matcher = linkUrl =~ VALID_PLAYER_URL
        assert matcher != null
        assert matcher.hasGroup()

        def videoId = matcher[0][2]

        for (elType in ['&el=embedded', '&el=detailpage', '&el=vevo', '']) {           
            def videoInfoUrl = "http://www.youtube.com/get_video_info?&video_id=$videoId$elType&ps=default&eurl=&gl=US&hl=en"
            //log("Loading video info: $videoInfoUrl")
            def videoInfoWebPage = new URL(videoInfoUrl).getText()
            def parameters = [:]
        
            videoInfoWebPage.split('&').each{item -> addParameter(item, parameters, '=')}
            if(parameters.containsKey('token')) {				
	            def formatUrlMapString = parameters['fmt_url_map']    
				def urlEncodedUrlMapString = parameters['url_encoded_fmt_stream_map']
				def allFormatUrlMap = [:]
				if (formatUrlMapString != null && formatUrlMapString.length() > 0 ) {
					URLDecoder.decode(formatUrlMapString,'UTF-8').split(',').each{item -> addParameter(item, allFormatUrlMap, '\\|')}						
				} else if (urlEncodedUrlMapString != null && urlEncodedUrlMapString.length() > 0 ) { 					
					URLDecoder.decode(urlEncodedUrlMapString,'UTF-8').split(',').each{item -> 
						def streamParams = [:]
						item.split('&').each{item2 -> addParameter(item2, streamParams, '=')}
						String urlKeyName = streamParams.containsKey('url') ? 'url' : 'conn'
						//String stream = URLDecoder.decode(streamParams['stream'],'UTF-8') //TODO stream is playpath
						allFormatUrlMap.put(streamParams['itag'], URLDecoder.decode(streamParams[urlKeyName],'UTF-8'))
					}
				}					
			   // get available formats for requested quality, sorted by quality from highest
			   def formatUrlMap = new LinkedHashMap()
			   if(requestedQuality == PreferredQuality.HIGH) {
				   // best quality, get the first from the list
				   sortAvailableFormatUrls(availableFormats, allFormatUrlMap, formatUrlMap)
				   def selectedUrl = formatUrlMap.entrySet().toList().head()
				   contentUrl = selectedUrl.getValue()
				   cacheKey = getCacheKey(linkUrl, selectedUrl.getKey())
			   } else if (requestedQuality == PreferredQuality.MEDIUM) {
				   // work with subset of available formats, starting at the position of format 35 and then take the best quality from there
				   sortAvailableFormatUrls(availableFormats.getAt(4..availableFormats.size-1), allFormatUrlMap, formatUrlMap)
				   def selectedUrl = formatUrlMap.entrySet().toList().head()
				   contentUrl = selectedUrl.getValue()
				   cacheKey = getCacheKey(linkUrl, selectedUrl.getKey())
			   } else {
				   // worst quality, take the last url
				   sortAvailableFormatUrls(availableFormats, allFormatUrlMap, formatUrlMap)
				   def selectedUrl = formatUrlMap.entrySet().toList().last()
				   contentUrl = selectedUrl.getValue()
				   cacheKey = getCacheKey(linkUrl, selectedUrl.getKey())
			   }			  
			   if(contentUrl != null) {
				   expiresImmediately = true
				   if(contentUrl.startsWith('http')) {
					   // http URL
					   def contentUrlParameters = [:]
					   contentUrl.split('&').each{item -> addParameter(item, contentUrlParameters, '=')}
					   if( contentUrlParameters['expire'] != null ) {   
						   //log(Long.parseLong(contentUrlParameters['expire']).toString())
						   expiryDate = new Date(Long.parseLong(contentUrlParameters['expire'])*1000)
						   expiresImmediately = false
					   }
				   } else {
				   		// rtmp URL
				   		def rtmpMatcher = contentUrl =~ 'rtmpe?://.*?/(.*)'
						def app = rtmpMatcher[0][1]
						// TODO load swf player URL from the HTML page
				   		contentUrl = "$contentUrl app=$app swfUrl=http://s.ytimg.com/yt/swfbin/watch_as3-vflg0Q-LP.swf swfVfy=1"
				   }	
			   }
                
                thumbnailUrl = parameters['thumbnail_url'] != null ? URLDecoder.decode(parameters['thumbnail_url']) : null
                break
            }
        }    
        return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: contentUrl, thumbnailUrl: thumbnailUrl, expiresOn: expiryDate, expiresImmediately: expiresImmediately, cacheKey: cacheKey)
    }
 
    def addParameter(parameterString, parameters, separator) {
        def values = parameterString.split(separator)
        if( values.length == 2 ) {    
             parameters.put(values[0], values[1])
        }
    }   

	def String getCacheKey(URL linkUrl, String qualityId) {
		"${linkUrl}_${qualityId}"
	}
		
	def sortAvailableFormatUrls(List formatIds, Map sourceMap, Map targetMap) {
		formatIds.each{formatId ->
			if(sourceMap.containsKey(formatId) ) {				
				 targetMap.put(formatId, sourceMap.get(formatId))
			}
		}
	}
    
    static void main(args) {
		// this is just to test
        YouTube extractor = new YouTube()
		
		assert extractor.extractorMatches( new URL("https://gdata.youtube.com/feeds/api/standardfeeds/top_rated?time=today") )
		assert extractor.extractorMatches( new URL("http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?time=today") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		
        Map links = ['alternate': new URL('https://www.youtube.com/watch?v=XZ3nEK1qSkA&amp;feature=youtube_gdata')] 
		//Map links = ['default': new URL('http://www.youtube.com/watch?v=C0D-yWvZw-Y&amp;feature=youtube_gdata')]
		
        ContentURLContainer result = extractor.extractUrl(links, PreferredQuality.MEDIUM)
        println "Result: $result"
    }
}