import org.serviio.library.metadata.*
import org.serviio.library.online.*

/**
 * WebResource extractor plugin for traileraddict.com
 *
 * @author Illico
 * @version 1.5
 */

class TrailerAddict extends WebResourceUrlExtractor {

	final int VERSION = 15
	final VALID_FEED_URL = '^http://www\\.traileraddict\\.com.*$'
	final LOGO = 'http://www.traileraddict.com/images/widgettop.png'
	final REGX_ITEMS = '<a href="(/trailer/.*?)"><img src="(.*?)" border="0" alt="(..*?)" title="(.*?)"'
	final BASE_URL = 'http://www.traileraddict.com'
	final VIDEO_INFO_HD_BASE_URL = 'http://www.traileraddict.com/fvarhd.php?tid='
	final VIDEO_INFO_SD_BASE_URL = 'http://www.traileraddict.com/fvar.php?tid='
	final REGX_VIDEO_ID = '<meta property="og:video" content="http://www.traileraddict.com/emd/.*?id=(\\d*)" />'
	final REGX_IMAGE_ID = '<meta property="og:image" content="http://www.traileraddict.com/img/(\\d*)" />'
	final REGX_IMAGE_URL = '<link rel="image_src" href="(.*?)" />'
	final REGX_TITLE = '<meta property="og:title" content="(.*?)" />'
	final REGX_FILEURL = 'fileurl=(.+?)\n'
	final REGX_WATCHINHD = 'watchplus'

	String getExtractorName() {
		return getClass().getName()
	}

	int getVersion() {
		return VERSION
	}

	boolean extractorMatches(URL feedUrl) {
		return feedUrl ==~ VALID_FEED_URL;
	}

	WebResourceContainer extractItems(URL resourceUrl, int maxItems) {
		String WebResourceTitle = getClass().getName()
		String WebResourceThumbnailUrl = LOGO
		List<WebResourceItem> items = []
		def trailermatcher = resourceUrl.getText() =~ REGX_ITEMS
		trailermatcher.each {
			String WebResourceItemTitle			= it[4]
			String WebResourceItemThumbnailUrl	= BASE_URL+it[2]
			String WebResourceItemUrl  			= BASE_URL+it[1]
			WebResourceItem item = new WebResourceItem(title: WebResourceItemTitle, additionalInfo: ['WebResourceItemThumbnailUrl':WebResourceItemThumbnailUrl,'WebResourceItemUrl':WebResourceItemUrl])
			items << item
		}
		return new WebResourceContainer(title: WebResourceTitle, thumbnailUrl: WebResourceThumbnailUrl, items: items)
	}

	ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {
		String url	= item.getAdditionalInfo()['WebResourceItemUrl']
		String webPage = new URL(url).getText()
		String VideoId = (webPage =~ REGX_VIDEO_ID)[0][1]
		String ImageUrl = (webPage =~ REGX_IMAGE_URL)[0][1]
		String Title    = (webPage =~ REGX_TITLE)[0][1]
		def Hdmatch     = webPage ==~ REGX_WATCHINHD
		loginfo("Title           : "+Title)
		loginfo("VideoId         : "+VideoId)
		loginfo("QualityRequested: "+ requestedQuality)
		loginfo("WatchInHd       : "+ Hdmatch)
		String VideoInfoUrl
		//if ( Hdmatch && (requestedQuality == PreferredQuality.HIGH)) {
		if ( requestedQuality == PreferredQuality.HIGH) {
			VideoInfoUrl = VIDEO_INFO_HD_BASE_URL + VideoId
			loginfo("VideoInfoUrl(HD): "+VideoInfoUrl);
		} else {
			VideoInfoUrl = VIDEO_INFO_SD_BASE_URL + VideoId
			loginfo("VideoInfoUrl(SD): "+VideoInfoUrl);
		}
		def VideoInfo = new URL(VideoInfoUrl).getText()
		String VideoUrl = ( VideoInfo =~ REGX_FILEURL )[0][1]
		VideoUrl = VideoUrl.replace( '%3A', ':').replace( '%2F', '/' ).replace( '%3F', '?' ).replace( '%3D', '=' ).replace( '%26', '&' ).replace( '%2F', '//' )
		loginfo("VideoUrl        : "+VideoUrl)
		loginfo("Time            : "+(System.currentTimeMillis()/1000).toInteger())
		//String ImageUrl = ( VideoInfo =~ '&image=(.*?)&')[0][1]
		//println "ImageUrl : "+ImageUrl
		def ExpireMatch = VideoUrl =~ 'http://.*expires=(\\d*)&token=.*'
		if (ExpireMatch.getCount() > 0 ) {
			loginfo("Expire           : "+ExpireMatch[0][1].toString())
			def cacheKey = getClass().getName() + "_${VideoId}_${requestedQuality}_"+(System.currentTimeMillis()/1000).toInteger()
			def expiryDate = new Date(Long.parseLong(( VideoUrl =~ 'http://.*expires=(\\d*)&token=.*')[0][1].toString())*1000)
			return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: VideoUrl, thumbnailUrl: ImageUrl, expiresOn: expiryDate, cacheKey : cacheKey)
		}else{
			loginfo("Expire          : No")
			return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: VideoUrl, thumbnailUrl: ImageUrl)
		}
	}

	private String loginfo(String text) {
		log(text);
		println(text);
	}

	static WebResourceContainer testURL(String url, int itemCount = 2) {
		TrailerAddict extractor = new TrailerAddict();
		URL resourceUrl = new URL(url);
		println "getExtractorName : " + extractor.getExtractorName();
		println "getVersion : " + extractor.getVersion();
		assert extractor.extractorMatches(resourceUrl), 'Url doesn\'t match for this WebResource plugin'
		println "extractorMatches : " + extractor.extractorMatches(resourceUrl);
		WebResourceContainer container = extractor.extractItems(resourceUrl, itemCount);
		assert container != null, 'Container is empty'
		assert container.items != null, 'Container contains no items'
		//assert container.items.size() == itemCount, 'Amount of items is invalid. Expected was ' + itemCount + ', result was ' + container.items.size()
		println "extractItems : " + container.items.size()
		println "***** HIGH *****";extractor.extractUrl(container.getItems()[1], PreferredQuality.HIGH);
		println "**** MEDIUM ****";extractor.extractUrl(container.getItems()[1], PreferredQuality.MEDIUM);
		println "***** LOW ******";extractor.extractUrl(container.getItems()[1], PreferredQuality.LOW);
		return container
	}

	static void main(args) {
		testURL("http://www.traileraddict.com",-1)	// Trailer Addict
		testURL("http://www.traileraddict.com/attraction/1",-1) // Trailer Addict : Top Trailers (page1)
	}
}