import org.serviio.library.online.*

/**
 * Content URL extractor plugin for NBA.com
 *
 * @author Illico
 *
 * @version 1.0
 */
class NBA extends FeedItemUrlExtractor {

	final VALID_FEED_URL = '(^http://www.nba.com/rss/.*.rss$)||(http://www.nba.com/.*.xml)'

	String getExtractorName() {
		return getClass().getName()
	}

	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()
		String VideoId = (webPage =~ 'var loadThisVideo = \'(.*?)\'')[0][1]
			assert VideoId != null, "Error : Source Url format should be something like http://www.nba.com/video/games/(???)/index.html"
			println "VideoId : "+VideoId; log("VideoId : "+VideoId);
		String VideoInfoUrl = "http://www.nba.com/"+VideoId+".xml"
		def VideoXml = new XmlParser().parse(VideoInfoUrl)
			assert VideoXml.name() == "video", "Error during Video info parsing"
		String VideoTitle = VideoXml.headline.text()
			println "VideoTitle : "+VideoTitle
		def VideofileHigh = VideoXml.files.file.findAll{ it.'@type' == "large" }
			assert VideofileHigh != null, "Error : could not find Video file"
		def VideoThumb = VideoXml.images.image.findAll{ it.'@width'.toInteger() < 150 && it.'@width'.toInteger() > 100 }
			assert VideoThumb !=null, "Error: could not find thumb url"
		String ContentUrl = "http://nba.cdn.turner.com/nba/big"+VideofileHigh[0].text()
		String ThumbnailUrl = VideoThumb[0].text()
			println "ContentUrl : "+ContentUrl
			println "ThumbnailUrl : "+ThumbnailUrl
		return new ContentURLContainer(contentUrl: ContentUrl, thumbnailUrl: ThumbnailUrl)
    }
	
    static void main(args) {
		// this is just to test
		NBA extractor = new NBA();
		Map videoLinks = ['default': new URL("http://www.nba.com/video/games/kings/2012/02/09/0021100387_okc_sac_recap.nba/index.html")]
		println "Name : " + extractor.getExtractorName();
		println "TestMatch : " + extractor.extractorMatches( new URL("http://www.nba.com/rss/highlights.rss"));
		println "**** HIGH ****";extractor.extractUrl(videoLinks, PreferredQuality.HIGH);
		println "**** MEDIUM ****";extractor.extractUrl(videoLinks, PreferredQuality.MEDIUM);
		println "**** LOW ****";extractor.extractUrl(videoLinks, PreferredQuality.LOW);	 
    }
}