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

/**
 * Generic LiveFeeds URL extractor plugin. 
 * Invoked by anyurl/LiveFeeds*
 *    
 * @author JHB50
 * Version 2 supporting UTF-8 BOM rss files
 * Version 3 added _ and space to regex for rtmp url's
 * Version 4 fix failure if no thumbnail specified
 *
 */
class LiveFeeds extends FeedItemUrlExtractor {

	final VALID_FEED_URL = '^http(s)*://.*?LiveFeeds.*?'
	List itemNode
	
	String getExtractorName() {
		return 'LiveFeeds'
	}
    
	boolean extractorMatches(URL feedUrl) {
		//get the rss contents if feed matches this groovy
		if (feedUrl ==~ VALID_FEED_URL)	{
			def rssPage = new URL(feedUrl.toString()).getText()
			def rssPagetmp = rssPage.replaceAll('&amp;','&')
			def rssPagenew = rssPagetmp.replaceAll('&','&amp;')
			//remove any unicode headers before <?xml
			rssPagenew = rssPagenew.find('(?s)<\\?xml.*')
			//now parse the rss contents into items
			def rssNodes = new XmlParser().parseText(rssPagenew)
			// and create a list of items
			itemNode = rssNodes.channel.item
		}
 		return feedUrl ==~ VALID_FEED_URL
	}

	ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
		def linkUrl = links.default  /* The <link> tag */
		def contentUrl = ""   /* The video to be played to be returned */
		def thumbnailUrl = "" /* The thumbnail to be displayed in DLNA menu - to be returned */
		// look at each item to find the link url and keep the match
		def matchedItem
		// set matchedItem with contents of Item with matching link
		itemNode.each { it -> if(it.link.text() == linkUrl.toString()) matchedItem = it }  
	        
		//now extract the stream url ... detect all characters that can be in livestream urls (?=@&.-)
		def mediaLink = matchedItem =~ '(?s)stream\\[attributes=\\{.*?url=(.*?)[,}]'
 		contentUrl = mediaLink[0][1]
        def thumbLink = matchedItem =~ '(?s)thumbnail\\[attributes=\\{.*?url=(.*?)[,}]'
        // ensure thumbnail was specified
		def matchthumbLink = matchedItem =~ '(?s)thumbnail\\[attributes=\\{.*?url=.*?[,}]'
		if (matchthumbLink) thumbnailUrl = thumbLink[0][1]

		//now check the stream type for audio 
		def mediaTypeAudio = matchedItem ==~ '.*?stream\\[attributes=\\{.*?type=audio.*?'
		MediaFileType fileType = MediaFileType.VIDEO;
		if( mediaTypeAudio == true ) fileType = MediaFileType.AUDIO

		def live = true
		
		return new ContentURLContainer(fileType: fileType, contentUrl: contentUrl, thumbnailUrl: thumbnailUrl, live: live)
	}

	static void main(args) {
		// this is just to test
		LiveFeeds extractor = new LiveFeeds()
		
		//assert extractor.extractorMatches( new URL("YourTest.rss"))
		assert extractor.extractorMatches( new URL("https://sites.google.com/site/serviiorss/LiveFeeds_US_News.rss"))

		//Map videoLinks = ['default': new URL('your http:// link')]
		Map videoLinks = ['default': new URL('http://cnbc')]
		ContentURLContainer result = extractor.extractUrl(videoLinks,PreferredQuality.HIGH)
		println "Result: $result"		 
	}
}