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

/**
 * WebResource extractor plugin for shoutcast.com.
 *
 * Version 3  - Apr. 26, 2012 - supports all Shoutcast options
 * Version 4  - Feb. 23, 2013 - display bit rate.

 * @author jhb50
 *
 * URL http://www.shoutcast.com
 * returns top 10 Shoutcast streams.
 *
 * URL http://www.shoutcast.com/radio/genre
 * returns top 10 genre streams.
 *
 * URL http://www.shoutcast.com/Internet-Radio/search_term
 * returns top 10 search_term streams.
 *
 */
class Shoutcast extends WebResourceUrlExtractor {
	
	final VALID_FEED_URL = '^(?:http?://)?(?:www\\.)?shoutcast\\.com.*?'
	
	String getExtractorName() {
		return 'Shoutcast'
	}
	
	boolean extractorMatches(URL feedUrl) {
		return feedUrl ==~ VALID_FEED_URL
	}
	
	int getVersion() {
		return 4
	}

	WebResourceContainer extractItems(URL resourceUrl, int maxItems) {
	
		log("Parsing with Shoutcast V4")

		String html = resourceUrl.getText()
		
		def titleMatcher = html =~ '(?s)<div id="tableheadtext".*?<h.>(.+?)</h.*?'
		println "titlematcher = $titleMatcher"
        println titleMatcher[0][1]
		String pageTitle = titleMatcher[0][1].trim()
		println "pagetitle = $pageTitle"
		
		List<WebResourceItem> items = []
		
		def itemsAdded = 0;
		String stationId
		String stationTitle
		
		// GET FEATURED STATIONS
		//<a class="featured_stations" id="1280356" name="977" href="http://yp.shoutcast.com/sbin/tunein-station.pls?id=1280356"></a>
		//<li class="secgen"><a class="secgen_a" id="1280356" name="977" href="http://yp.shoutcast.com/sbin/tunein-station.pls?id=1280356">.977 Hitz</a></li> 
		def featuredMatcher = html =~ '(?s)<a class="secgen_a".*?pls.id=(.+?)">(.*?)<.*?'
		for( int i = 0; i < featuredMatcher.size() && (maxItems == -1 || itemsAdded < maxItems); i++ ) {
			stationId    = featuredMatcher[i][1].trim()
			stationTitle = featuredMatcher[i][2].trim()
			WebResourceItem item = new WebResourceItem(title: stationTitle, additionalInfo: ['stationId':stationId])
			println "item = $item"
			items << item
			itemsAdded++			
		}
		
		// GET TOP 10 or GENRE
		//<a class="playbutton clickabletitle" id="21585" name="idobi Radio: New. Music. Unfiltered. ido..." title="idobi Radio: New. Music. Unfiltered. idobi.com" href="http://yp.shoutcast.com/sbin/tunein-station.pls?id=21585"> idobi Radio: New. Music. Unfiltered. ido...</a> 
		//<a class="playbutton clickabletitle" name="Absolute Blues Hits (1.FM TM)" id="1270282" title="Absolute Blues Hits (1.FM TM)" href="http://yp.shoutcast.com/sbin/tunein-station.pls?id=1270282"> Absolute Blues Hits (1.FM TM)</a> 
        //<a class="playbutton clickabletitle" name="RadioIntensa.com" id="236205" title="RadioIntensa.com" href="http://yp.shoutcast.com/sbin/tunein-station.pls?id=236205"> RadioIntensa.com</a> 
		//def stationMatcher = html =~ '(?s)<a class="playbutton clickabletitle" id="(.+?)".*?title="(.+?)".*?<a href="/radio/(.*?)"'
		def stationMatcher = html =~ '(?s)<a class="playbutton.*?clickabletitle".*?id="(.+?)".*?title="(.+?)".*?<div class="dirbitrate">(.*?)<'
		for( int i = 0; i < stationMatcher.size() && (maxItems == -1 || itemsAdded < maxItems); i++ ) {
			stationId    = stationMatcher[i][1].trim()
			stationTitle = "(" + stationMatcher[i][3].trim() + "KB) " + stationMatcher[i][2].trim()
			WebResourceItem item = new WebResourceItem(title: stationTitle, additionalInfo: ['stationId':stationId])
			println "item = $item"
			items << item
			itemsAdded++			
		}

		return new WebResourceContainer(title: pageTitle, items: items)
	}
	
	ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {		
		String stationId = item.getAdditionalInfo()['stationId']
		assert stationId != null

		String playerHtml = new URL("http://yp.shoutcast.com/sbin/tunein-station.pls?id=$stationId").getText()
		println "http = $playerHtml"
		def linkMatcher = playerHtml =~ '(?s)playlist.*?File1=(.*?)Title.'
		String streamLink = linkMatcher[0][1].trim()
		println "streamLink = $streamLink"

		return new ContentURLContainer(fileType: MediaFileType.AUDIO, contentUrl: streamLink, live: true)
	}
	
	
	static void main(args) {
		// this is just to test
		Shoutcast extractor = new Shoutcast()
				
		assert extractor.extractorMatches( new URL("http://www.shoutcast.com/") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		

		WebResourceContainer container = extractor.extractItems( new URL("http://www.shoutcast.com/"), -1)
		//WebResourceContainer container = extractor.extractItems( new URL("http://www.shoutcast.com/radio/country%20blues"), -1)
		println container
		
		ContentURLContainer result = extractor.extractUrl(container.getItems()[3], PreferredQuality.MEDIUM)
		print result		
	}
}