import org.serviio.library.metadata.*
import org.serviio.library.online.*

/**
 * John Cleese content URL extractor plugin. 
 * http://www.johncleesepodcast.co.uk/cleeseblog/rss.xml
 * http://johncleesepodcast.co.uk/cleeseblog/
 *   
 * @author JHB50
 *
 */
class Cleeseblog extends FeedItemUrlExtractor {

	final VALID_FEED_URL = '^http(s)*://www.johncleesepodcast.co.uk/cleeseblog/rss.xml.*$'
	def saveUrl 

	String getExtractorName() {
		return getClass().getName()
	}
    
	boolean extractorMatches(URL feedUrl) {
                //println "feedUrl = " + feedUrl
		saveUrl = "$feedUrl"  		//save rss url in string format for getting the feed later
 		//println "saveUrl = " + saveUrl
 		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 */

		// display the <link> tag
		println "linkUrl = " + linkUrl

		//goback and get the feed url
                def rssNode = new XmlParser().parse(saveUrl)
		

		// get a list of items
		List itemNode = rssNode.channel.item
		//println "itemNode = " + itemNode
                println " "

		// look at each item to find the link url and keep the match
                
		def matchedItem
		
		// this proves the match is made but matchedItem is not set.
		itemNode.each { it -> if(it.link.text() == linkUrl) matchedItem = it else println "x"+it.link.text()+"x"+linkUrl+"x" }  

                println " "
		println "matchedItem = " + matchedItem
                println " "
		
		// try zips suggestion
		def matchedNode = itemNode.find { it -> it.link.text() == linkUrl }
	
		println "matchedNode = " + matchedNode
                println " "
		
		// try my alternate method
		def matchedItem2 = itemNode.link.find { it -> it.link.text() == linkUrl}   

		println "matchedItem2 = " + matchedItem2
                println " "
	
		return null
	}

	static void main(args) {
		// this is just to test
		Cleeseblog extractor = new Cleeseblog()
		
		//assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		assert extractor.extractorMatches( new URL("http://www.johncleesepodcast.co.uk/cleeseblog/rss.xml") )
		
		Map videoLinks = ['default': new URL('http://www.johncleesepodcast.co.uk/cleeseblog/2008/10/john-cleese-podcast-34-headmaster.html')]
		ContentURLContainer result = extractor.extractUrl(videoLinks, PreferredQuality.MEDIUM)
		println "Result: $result"		 
	}
}






