import groovy.util.Node

import java.util.List

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

/**
 * Content URL extractor plugin for Arte
 * 
 * List of feed : http://videos.arte.tv/fr/videos/meta/index-3188674-3223978.html
 * Url ex: http://videos.arte.tv/fr/do_delegate/videos/programmes/360_geo/index-3188704,view,rss.xml
 * 
 * @author Illico
 *
 * Version : 1.0
 */
class Arte extends FeedItemUrlExtractor {

    final EXTRACTOR_NAME = 'Arte';
    final VALID_FEED_URL = '(^http://videos.arte.tv.*rss.xml$)'
	final VALID_THUMB_URL = '.*<link rel="image_src".*'
	final VALID_VIDEO_URL = '.*vars_player.videorefFileUrl.*'
    final VALID_PLAYER_URL = '.*var url_player = .*'
	final PREFERRED_LANG = 'fr'; // Default French (fr), should be Deutch (de)
   
    String getExtractorName() {
        return EXTRACTOR_NAME
    }
    
    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 webPage = linkUrl.getText()
		
		// Parse Thumbnail Url 
        // ex: <link rel="image_src" href="http://videos.arte.tv/image/web/i18n/view/07_01_12_Schottland_jpg_1-6307522-imageData-5049853,h,102,w,180.jpg"/>
		def matcher1 = webPage =~ VALID_THUMB_URL
		assert matcher1 != null
		def linkParts1 = matcher1[0].toString().split('"')
		def ThumbnailUrl = linkParts1[3].toString()
		log('ThumbnailUrl: '+ ThumbnailUrl)        

		// Parse VideoRefXmlFileUrl
        // ex: vars_player.videorefFileUrl = "http://videos.arte.tv/fr/do_delegate/videos/360_geo-6304540,view,asPlayerXml.xml"
		def matcher2 = webPage =~ VALID_VIDEO_URL
		assert matcher2 != null
		def linkParts2 = matcher2[0].toString().split('"')
		def VideoRefXmlFileUrl = linkParts2[1].toString()
        
        // Parse Player Url
        // ex: var url_player = "http://videos.arte.tv/blob/web/i18n/view/player_23-3188338-data-5044926.swf";
        def matcher3 = webPage =~ VALID_PLAYER_URL
        assert matcher3 != null
        def linkParts3 = matcher3[0].toString().split('"')        
        def RTMP_swfUrl = linkParts3[1].toString()

        // Parse VideoLangXmlFile Url
        def XmlNodes = new XmlParser().parse(VideoRefXmlFileUrl)
        assert XmlNodes.name() == 'videoref'
        String VideoLangXmlFileUrl = XmlNodes.videos.video.findAll{ it.'@lang' =~ PREFERRED_LANG }.'@ref'[0]
        def VideoNodes = new XmlParser().parse(VideoLangXmlFileUrl)
        assert VideoNodes.name() == 'video'
        
        // Parse Video PreferredQuality Url
        // ex:
        // <urls>
        //	<url quality="sd">rtmp://artestras.fcod.llnwd.net/a3903/o35/mp4:geo/videothek/ALL/arteprod/A7_SGT_ENC_06_045793-000-B_PG_MQ_FR?h=ea494c5fcfba40cdc1ad18aecd3d7a92</url>
        //	<url quality="hd">rtmp://artestras.fcod.llnwd.net/a3903/o35/mp4:geo/videothek/ALL/arteprod/A7_SGT_ENC_08_045793-000-B_PG_HQ_FR?h=103cb7c5b550b8555ff7dcc76df11781</url>
        // </urls>
        String VideoUrl = ""
        assert VideoNodes.urls.url.size() == 2
        if(requestedQuality == PreferredQuality.HIGH) {
            VideoUrl = VideoNodes.urls.url[1].text()
            println "VideoUrl(HD): " + VideoUrl
        } else {
            VideoUrl = VideoNodes.urls.url[0].text()
            println "VideoUrl(SD): " + VideoUrl
        }
        def linkParts4 = VideoUrl.toString().split('/')
        def RTMP_App = linkParts4[3].toString()+"/"+linkParts4[4].toString(); println "RTMP_App: $RTMP_App"; // a3903/o35
        def RTMP_Server = linkParts4[2].toString()+":443"; println "RTMP_Server: rtmp://$RTMP_Server"; //rtmp://artestras.fcod.llnwd.net:443
        def linkParts5 = VideoUrl.toString().split('mp4:')
        def RTMP_playpath = linkParts5[1].toString(); println "RTMP_playpath: $RTMP_playpath"; // geo/videothek/ALL/arteprod/A7_SGT_ENC_06_045793-000-B_PG_MQ_FR?h=ea494c5fcfba40cdc1ad18aecd3d7a92
        
        def contentUrl = "rtmp://" + RTMP_Server + " app=" + RTMP_App + " swfUrl=" + RTMP_swfUrl + " playpath=mp4:" + RTMP_playpath + " swfVfy=1"
        
        log('ContentUrl(rtmp): ' + contentUrl)
        return new ContentURLContainer(contentUrl: contentUrl, thumbnailUrl: ThumbnailUrl)

    }
	
    static void main(args) {
		// this is just to test
        Arte extractor = new Arte()
		
        Map videoLinks = ['default': new URL("http://videos.arte.tv/fr/videos/360_geo-6304540.html")] 
        
        println "Name : " + extractor.getExtractorName();
        println "TestMatch : " + extractor.extractorMatches( new URL("http://videos.arte.tv/fr/do_delegate/videos/programmes/360_geo/index-3188704,view,rss.xml"));        
        extractor.extractUrl(videoLinks, PreferredQuality.HIGH);println "**** HIGH ****"
        extractor.extractUrl(videoLinks, PreferredQuality.MEDIUM);println "**** MEDIUM ****"
        extractor.extractUrl(videoLinks, PreferredQuality.LOW);println "**** LOW ****"
    }
}