import groovy.json.JsonSlurper

import org.apache.commons.lang.StringEscapeUtils
import org.serviio.library.metadata.*
import org.serviio.library.online.*

/**
 * Vimeo.com content URL extractor plugin. 
 * 
 * Based on youtube_dl Python script (http://rg3.github.com/youtube-dl/)
 * http://code.google.com/p/vimeoxbmc/
 *  
 * @author Petr Nejedly
 *
 */
class Vimeo extends FeedItemUrlExtractor {

    final VALID_ITEM_URL = 'https?://((www|player)\\.)?vimeo\\.com/.*?([0-9]+)'
    final VALID_FEED_URL = '^http(s)*://.*vimeo\\..*$'
	
    String getExtractorName() {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
    
	public int getVersion() {
		return 4
	}

	ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
        def linkUrl = links.default
        def contentUrl
        
		def videoPageHtml = openURL(linkUrl, getFFmpegUserAgent())
		def encodedDataConfigUrl = (videoPageHtml =~ '(?s)data-config-url="(.+?)"')[0][1]
		def dataConfigUrl = StringEscapeUtils.unescapeHtml(encodedDataConfigUrl)	
		def dataConfig = openURL(new URL(dataConfigUrl), getFFmpegUserAgent())
		
		assert dataConfig != null
		Map config = new JsonSlurper().parseText(dataConfig)
		
		def thumbnailUrl = config.video.thumbs.base
		
		def files = [ 'hd': [], 'sd': [], 'other': []]
		
		def essences = config.request.files.progressive.sort { it.height }
		
		def selectedEssence = findSuitableEssence(essences, requestedQuality)
				
		contentUrl = selectedEssence.url
		return new ContentURLContainer(contentUrl: contentUrl, thumbnailUrl: thumbnailUrl)
    }
	
	private def Map findSuitableEssence(List essences, PreferredQuality requestedQuality) {
		if(requestedQuality == PreferredQuality.LOW || essences.size() <= 1) {
			// worst quality, get the first from the list
			return essences.head()
		} else if (requestedQuality == PreferredQuality.MEDIUM) {
			// get item from the middle
			return essences.get(Math.round(essences.size()/2).toInteger())
		} else {
			// best quality, take the last url
			return essences.last()
		}
	}
    
    static void main(args) {
		// this is just to test
        Vimeo extractor = new Vimeo()
		
		assert extractor.extractorMatches( new URL("http://vimeo.com/channels/stereoscopy/videos/rss") )
		assert extractor.extractorMatches( new URL("http://vimeo.com/channels/saisouljourns/videos/rss") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		
		Map links = ['default': new URL('http://vimeo.com/channels/saisouljourns#18681973')]
		//Map links = ['default': new URL('https://vimeo.com/channels/151161/66744684')]
				
        ContentURLContainer result = extractor.extractUrl(links, PreferredQuality.HIGH)
        println "Result: $result"
    }
}