import org.serviio.library.metadata.*
import org.serviio.library.online.*

/**
 * Tv3Play.se content URL extractor plugin. - 
 *
 * @version 0.1a
 * 
 * http://www.tv3play.se/rss/mostviewed
 *  
 * @author Tomas Falemo
 *
 */
class Tv3Play extends FeedItemUrlExtractor {
    
    final VALID_FEED_URL = '^http(s)*://www.tv3play.se/rss/.*$'   

    String getExtractorName() {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
    
    ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
        def linkUrl = links.default
        def progID
		//log('linkUrl:'+linkUrl)
		
		def contentUrl
		
		def progHtml
		def progurl = new URL(''+linkUrl)
		def progconnection = progurl.openConnection()
		if(progconnection.responseCode == 200){
			progHtml = progconnection.content.text
			def progmatcher = (progHtml =~ '\\.*http\\:\\/\\/www\\.tv3play\\.se\\/play\\/(\\d+)\\/\\.*')
			assert progmatcher != null
			if(progmatcher.size() > 0)
			{
				//println progmatcher [0][1]
				progID = progmatcher[0][1]
			} 
			
			def contentHtml
			def url = new URL('http://viastream.viasat.tv/PlayProduct/'+progID)
			def connection = url.openConnection()
			if(connection.responseCode == 200){
				contentHtml = connection.content.text
			}
			else{
				return null
			}

			// example of match: rtmp://cp90686.edgefcs.net/ondemand/flash/sweden/tv3/Lyxfallan/Season9/lyxfallan_903
			def matcher = (contentHtml =~ '.*(rtmp.*)\\]\\]')
			assert matcher != null
			if(matcher.size() > 0)
			{
				contentUrl = matcher[0][1]
			}
			else
			{
				//println contentHtml
				return null
			}		
		}
		else
		{
			return null
		}		
		
		//println contentUrl
        return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: contentUrl)
    }
    
    static void main(args) {
		// this is just to test
        Tv3Play extractor = new Tv3Play()
		
		assert extractor.extractorMatches( new URL("http://www.tv3play.se/rss/mostviewed") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		
        Map links = ['default': new URL('http://www.tv3play.se/play/234829/')] 
        ContentURLContainer result = extractor.extractUrl(links, PreferredQuality.MEDIUM)
        println "Result: $result"
    }
}