import groovy.json.JsonSlurper
import org.serviio.library.metadata.*
import org.serviio.library.online.*
import org.serviio.util.*

/**
 * WebResource Refresh Plug-in for Repository URLs 
 * Invoked by http://www.refresh.com
 *    
 * @author JHB50
 * Version 1 4/30/2012
 *
 * All WebResource Based folders are automatically listed by name
 * Just click to initiate a Refresh of that folder.
 *
 * Prereqs:
 * - Installation of curl.exe
 * - Installation of C:\Program Files\Serviio\lib\ffmpeg.bat 
 * - Update of C:\Program Files\Serviio\bin\ServiioService.exe.vmoptions
 *   to include -Dffmpeg.location="C:\Program Files\Serviio\lib\ffmpeg.bat"
 * For complete instructions, see wiki http://wiki.serviio.org/doku.php?id=refresh_on_demand
 *
 */
class Refresh extends WebResourceUrlExtractor {
	
	final VALID_FEED_URL = '^http(s)*://www.refresh.com.*?'
	
	String getExtractorName() {
		return 'Refresh'
	}
 	boolean extractorMatches(URL feedUrl) {
		return feedUrl ==~ VALID_FEED_URL
	}
   
	WebResourceContainer extractItems(URL resourceUrl, int maxItems) {
	
		println "resourceUrl = $resourceUrl"
		List<WebResourceItem> items = []
		def itemsAdded = 0
		def id =  0
		String pageTitle = ""
		String pageThumb = ""
		String feedTitle = ""
		
		//# Use curl to get the repository 
		//# W32 users Must use 32 bit version of curl installed in System32 
		//# W64 users Must use 64 bit version of curl installed in SysWOW64
		//# curl -X GET http://localhost:23423/rest/repository
		
		String command = "curl -X GET http://localhost:23423/rest/repository "
		//# println command
		
		//# execute the string
		Process repository = command.execute()                 
		//# Get repository online entries
		//# <onlineRepository>
		//# 1=	<id>3</id>
		//# 2=	<repositoryType>LIVE_STREAM</repositoryType>
		//# 3=	<contentUrl>http://1651.live.streamtheworld.com/CBC_R2_CLASS_H_SC</contentUrl>
		//# 4=	<fileType>AUDIO</fileType>
		//# 5=	<repositoryName>CBC Classical</repositoryName>
		//# 6=	<enabled>false</enabled>
		//# </onlineRepository>

		
		def repositoryMatcher = repository.text =~ '(?ms).*?<onlineRepository>.*?<id>(.*?)</id>.*?<repositoryType>(.*?)</repositoryType>.*?<contentUrl>(.*?)</contentUrl>.*?<fileType>(.*?)</fileType>.*?<repositoryName>(.*?)</repositoryName>.*?<enabled>(.*?)</enabled>.*?'
		//println repositoryMatcher.size()			//#
		for( int i = 0; i < repositoryMatcher.size() && (maxItems == -1 || itemsAdded < maxItems); i++ ) {
			id = repositoryMatcher[i][1].trim()
			def feedType = repositoryMatcher[i][2].trim()
			def mediaUrl = repositoryMatcher[i][3].trim()
			def mediaType = repositoryMatcher[i][4].trim()
			feedTitle = repositoryMatcher[i][5].trim()
			def Mode = repositoryMatcher[i][6].trim()
			if (feedType != "WEB_RESOURCE" || mediaType != "VIDEO" || Mode != "true" || mediaUrl == "http://www.refresh.com") continue
			println id
			feedTitle = id + ": " + feedTitle
			println feedTitle
			WebResourceItem item = new WebResourceItem(title: feedTitle, additionalInfo: ['resourceUrl':resourceUrl,'itemnum':i,'id':id ])

			println "Item = $item\r\n"																			//#

			items << item
			itemsAdded++
		}
		
		return new WebResourceContainer(title: pageTitle, thumbnailUrl: pageThumb, items: items)
	}

	ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {		
		//# Video Title for menu display
		String feedTitle = item.title
		String itemnum = item.getAdditionalInfo()['itemnum']
		String id = item.getAdditionalInfo()['id']

		String feedUrl = "rtsp://a1709.l1856953708.c18569.g.lm.akamaistream.net:554/D/1709/18569/v" + id + "/reflector:53708"
		String thumbnailUrl = "https://sites.google.com/site/serviiorss/refresh.jpg"
		
		return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: feedUrl, thumbnailUrl: thumbnailUrl, live: true)
	}

	static void main(args) {
		// this is just to test
		Refresh extractor = new Refresh()
		
		assert extractor.extractorMatches( new URL("http://www.refresh.com"))
		
		WebResourceContainer container  = extractor.extractItems( new URL("http://www.refresh.com"),-1 )   
		println container

		ContentURLContainer result = extractor.extractUrl(container.getItems()[0], PreferredQuality.MEDIUM)
		println "Result: $result"		 
	}
}