
import org.serviio.library.metadata.*
import org.serviio.library.online.*
import org.serviio.util.*

/**
 * Content URL extractor plugin for rtve.es video feeds.
 *
 * @author Petr Nejedly
 *
 */
class RTVE extends FeedItemUrlExtractor {
	
	final VALID_FEED_URL = '^(?:https?://)?(?:www\\.)?rtve\\.es/.*$'
	
	String getExtractorName() {
		return 'RTVE'
	}
	
	boolean extractorMatches(URL feedUrl) {
		return feedUrl ==~ VALID_FEED_URL
	}
	
	ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
		def linkUrl = links.default
		def contentUrl
		def thumbnailUrl
		
		def matcher = linkUrl =~ '/(\\d+)/?$'
		assert matcher != null
		assert matcher.hasGroup()
		
		def videoId = matcher[0][1]
		String videoInfoUrl = "http://www.rtve.es/swf/data/es/videos/video${getPathFromNumber(videoId)}/${videoId}.xml"
		String videoInfoXml = new URL(videoInfoUrl).getText()
		
		def assetIdMatcher = videoInfoXml =~ '(?s)assetDataId::(\\d+)'
		assert assetIdMatcher != null
		assert assetIdMatcher.hasGroup()		
		def assetId = assetIdMatcher[0][1]
		
		def thumbnailMatcher = videoInfoXml =~ '(?s)<image>(.+?)</image>'
		assert thumbnailMatcher != null
		assert thumbnailMatcher.hasGroup()
		thumbnailUrl = thumbnailMatcher[0][1]
		
		String assetInfoUrl = "http://www.rtve.es/scd/CONTENTS/ASSET_DATA_VIDEO${getPathFromNumber(assetId)}/ASSET_DATA_VIDEO-${assetId}.xml"
		def assetContentNode = new XmlParser().parse( assetInfoUrl )
		
		int prefixLength = "/deliverty/demo/resources/".size()		
		String defaultLocation = assetContentNode.'@defaultLocation'[-prefixLength..-1]	
		contentUrl = "http://www.rtve.es/resources/TE_NGVA${defaultLocation}"
		
		
		return new ContentURLContainer(contentUrl: contentUrl, thumbnailUrl: thumbnailUrl)
	}
	
	def String getPathFromNumber(String number) {
		String lastFourCharacters = number[-4..-1]
		String path = ""
		lastFourCharacters.reverse().getChars().each { it -> path = path + '/' + it }
		return path
	}
		
	static void main(args) {
		// this is just to test
		RTVE extractor = new RTVE()
		
		assert extractor.extractorMatches( new URL("http://www.rtve.es/api/programas/1705/contents.mrss") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		
		Map videoLinks = ['default': new URL('http://www.rtve.es/alacarta/videos/redes/redes-alma-esta-red-del-cerebro-avance/1246966/')]
		ContentURLContainer result = extractor.extractUrl(videoLinks, PreferredQuality.MEDIUM)
		println "Result: $result"		 
	}
}