import org.serviio.library.metadata.*
import org.serviio.library.online.*

/**
 * Tv3Play.se content URL extractor plugin. - 
 *
 * @version 1.2
 * 
 * http://www.tv3play.se/rss/recent
 * http://www.tv3play.se/rss/mostviewed
 * http://www.tv3play.se/rss/highestrated
 *  
 * @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) {
        // http://www.tv3play.se/play/254935/
	    def linkUrl = ""+links.default
		// [http:, , www.tv3play.se, play, 254935]
		def linkparts =  linkUrl.split("/")
		// 254935
		def progID = linkparts[linkparts.length-1]
		
		def contentUrl
			
		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
		}
		
		// For finding the stream
		// example of match: rtmp://cp90686.edgefcs.net/ondemand/flash/sweden/tv3/Lyxfallan/Season9/lyxfallan_903
		def matcher = (contentHtml =~ '.*(rtmp.*)\\]\\]')

		log('Was RTMP url found?')
		if (matcher.size() == 0)
		{
			log('No. Geoblocked?')
			// Try again, maybe GeoBlocked?
			// URL to next page should be in the format of http://viastream.viasat.tv/extra/extraN.php?XXXXXX
			def geoblockmatcher = (contentHtml =~ '.*(http.*extraN.*)\\]\\]')
			assert geoblockmatcher != null
			def geoblockUrl = new URL(geoblockmatcher[0][1])
			log('GeoblockURL found: ' + geoblockUrl)
			def connection2 = geoblockUrl.openConnection()
			def geoblockcontentHtml
			if(connection2.responseCode == 200){
				geoblockcontentHtml = connection2.content.text
			}
			else{
				return null
			}
			
			// Note: This is not a pure XML file, so the regex is different and does not end with ]]
			matcher = (geoblockcontentHtml =~ '.*(rtmp.*)\\<\\/')
			assert matcher != null

			if (matcher.size() > 0)
			{
			log('Found content url!')
				contentUrl = matcher[0][1]
				log('ContentUrl: ' + contentUrl)
			
				contentUrl = contentUrl + ' swfUrl=http://flvplayer-viastream-viasat-tv.origin.vss.viasat.tv/play/swf/player110420.swf swfVfy=1'
			} else {
				log('Did not find url :(')
				return null
			}

		} else if (matcher.size() > 0)
		{
			log('RTMP url found in first try!')
			contentUrl = matcher[0][1]
			def parts = contentUrl.split('/mp4:')
			
			if(parts.size() > 1)
			{
				contentUrl = parts[0] + '/ swfUrl=http://flvplayer-viastream-viasat-tv.origin.vss.viasat.tv/play/swf/player110420.swf playpath=mp4:'+parts[1]+' swfVfy=1'
			}
			else 
			{
				contentUrl = contentUrl + ' swfUrl=http://flvplayer-viastream-viasat-tv.origin.vss.viasat.tv/play/swf/player110420.swf swfVfy=1'
			}
		}
		else
		{
			log('No url was found!')
			return null
		}

		// For finding Thumbnail
		// example of match: http://viastream.viasat.tv/sites/viastream.viasat.tv/files/category_pictures/batmanTax.jpg
		def imageMatcher = (contentHtml =~ '.*(http.*\\.jpg|http.*\\.gif)\\]\\]')
		def thumbUrl = ""
		if(imageMatcher.size() > 0)
		{
			thumbUrl = imageMatcher[0][1]
		}
        return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: contentUrl, thumbnailUrl: thumbUrl)
    }
    
    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"
        Map links = ['default': new URL('http://www.tv3play.se/play/256219/')] 
        ContentURLContainer result = extractor.extractUrl(links, PreferredQuality.MEDIUM)
        println "Result: $result"
        links = ['default': new URL('http://www.tv3play.se/play/256420/')] 
        result = extractor.extractUrl(links, PreferredQuality.MEDIUM)
        println "Result2: $result"
		
    }
}
