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

/**
 * Tv8Play.se content URL extractor plugin. - 
 *
 * @version 1.1
 * 
 * http://www.tv8play.se/rss/recent
 * http://www.tv8play.se/rss/mostviewed
 * http://www.tv8play.se/rss/highestrated
 *  
 * @author Kovács Z. Ottó based on Tomas Falemo's and FoH's TV3 Play plugin
 *
 */
class Tv8Play extends FeedItemUrlExtractor {
    
    final VALID_FEED_URL = '^http(s)*://www.tv8play.se/rss/.*$'   

    String getExtractorName() {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
    
    ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
	// This is for extracting programme ID
	def linkUrl = ""+links.default 			// Expected result in format "http://www.tv8play.se/play/257152/"
	def linkparts =  linkUrl.split("/")		// Expected result in format "[http:, , www.tv8play.se, play, 257152]"
	def progID = linkparts[linkparts.length-1]	// Expected result in format "257152"
	
	def contentUrl	// Stores URL match later on
	def contentHtml // Stores programme page with (hopefully) the link to the stream
	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 link
	// Example of match: "rtmp://mtgfs.fplive.net/mtg/flash/sweden/tv8/enplatsisolen/home_or_away/season3/aplaceinthesun_302"
	def matcher = (contentHtml =~ '.*(rtmp.*)\\]\\]')

	log('Checking if RTMP url was found...')
	if (matcher.size() == 0) {
		// Some shows are Geoblocked and then the link to the stream is in another page.
		// URL to next page should be in the format of "http://viastream.viasat.tv/extra/extraN.php?XXXXXX"
		log('No, did not find RTMP url. Checking if show is Geoblocked...')

		def geoblockmatcher = (contentHtml =~ '.*(http.*extraN.*)\\]\\]')	// New matcher
		assert geoblockmatcher != null
		def geoblockUrl = new URL(geoblockmatcher[0][1])
		log('Found Geoblock URL!')
		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 ]] like the previous matcher
		matcher = (geoblockcontentHtml =~ '.*(rtmp.*)\\<\\/')
		assert matcher != null

		if (matcher.size() > 0)	{
			log('Found Geoblock content url!')
			contentUrl = matcher[0][1]
		
			contentUrl = contentUrl + ' swfUrl=http://flvplayer-viastream-viasat-tv.origin.vss.viasat.tv/play/swf/player110420.swf swfVfy=1'
		} else {
			log('Did not find Geoblocked 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/imagecache/episode_image/images/assets/automatic/26477a918bb11bb861ae0fcdc098559d-4jpg.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)
    }
    
    // Function for testing purposes
    static void main(args) {
	Tv8Play extractor = new Tv8Play()
		
	assert extractor.extractorMatches( new URL("http://www.tv8play.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.tv8play.se/play/257152/')] 
        //ContentURLContainer result = extractor.extractUrl(links, PreferredQuality.MEDIUM)
        //println "Result: $result"
        Map links = ['default': new URL('http://www.tv8play.se/play/257326/')] 
        ContentURLContainer result = extractor.extractUrl(links, PreferredQuality.MEDIUM)
        println "Result: $result"
        links = ['default': new URL('http://www.tv8play.se/play/253119/')] 
        result = extractor.extractUrl(links, PreferredQuality.MEDIUM)
        println "Result2: $result"		
    }
}
