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

import groovy.json.JsonSlurper

/**
 * WebResource extractor plugin for Disney Junior
 *
 * example : Mickey (fr) : http://www.disney.fr/disney-junior/contenu/videos.jsp?b=mch
 * example : Mickey (uk) : http://www.disney.co.uk/disney-junior/content/video.jsp?b=mch
 *
 * @author Illico
 * @version 0.3
 *
 */

class DisneyJunior extends WebResourceUrlExtractor {

	final int VERSION = 3
	final VALID_URL = '^(http://www.disney.(fr|co.uk)/disney-junior/(contenu|content)/video(s*).jsp).*$'
	final LOGO_DISNEY = 'http://www.disney.fr/cms_inc/disney-junior/views/nav_brand_html/images/disney_logo.png'
	final REGEX_WEBTHUMB = '<li class="video_brand_promo.+?\n.+?data-code="(.+?)" data-originpromo="(.+?)".+?\n.+?\n.+?\n.+?data-hover="(.+?)"'
	final REGEX_ITEMTHUMB = '<div class="promo".+?\n.+?\n.+?<img src="(.+?)"'
	final REGEX_JSONPLAYLIST = '<div id="playlistJsonString".*>(.*?)</div>'
	String BaseUrl
	String BaseVideosUrl

	String getExtractorName() {
		return "Disney Junior"
	}

	int getVersion() {
		return VERSION
	}

	boolean extractorMatches(URL feedUrl) {
		return feedUrl ==~ VALID_URL
	}

	WebResourceContainer extractItems(URL resourceUrl, int maxItems) {
		String WebResourceTitle = "DISNEY JUNIOR"
		List<WebResourceItem> items = []
		loginfo("resourceUrl : "+resourceUrl);
		def matchbaseurl = resourceUrl =~ VALID_URL
		assert matchbaseurl.getCount() > 0, "Error : URL not compatible"
		// Extraction base url
		BaseUrl = "http://www.disney."+matchbaseurl[0][2]
		loginfo("BaseUrl : "+BaseUrl);
		// Extraction base video url
		BaseVideosUrl = matchbaseurl[0][1]
		loginfo("BaseVideosUrl : "+BaseVideosUrl);
		// Extraction WebResourceThumbnailUrl
		String pageContent = resourceUrl.getText("utf-8")
		def matchwebthumb = pageContent =~ REGEX_WEBTHUMB
		assert matchwebthumb.getCount() > 0, "Error : Page content not compatible"
		String WebResourceThumbnailUrl = BaseUrl+matchwebthumb[0][3]
		loginfo("WebResourceThumbnailUrl : "+WebResourceThumbnailUrl)
		// Extraction playlist
		def matchplaylist = pageContent =~ REGEX_JSONPLAYLIST
		assert matchplaylist.getCount() > 0, "Error : Page content not compatible"
		def plst = get_json(matchplaylist[0][1])
		plst.playlist[0].items.each {
			String ItemTitle = it.pageTitle
			String ItemUrlId = it.urlId
			String ItemUrl	= it.media.progressive
			WebResourceItem item = new WebResourceItem(title: ItemTitle, additionalInfo: ['ItemUrlId': ItemUrlId, 'ItemUrl': ItemUrl])
			items << item
		}
		//items = items.sort{ it.title } // Tri par titre
		return new WebResourceContainer(title: WebResourceTitle, thumbnailUrl: WebResourceThumbnailUrl, items: items)
	}

	ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {
		String MediaUrlId = item.getAdditionalInfo()['ItemUrlId']
		loginfo("MediaUrlId     : "+MediaUrlId);
		URL murl = new URL(BaseVideosUrl+"?v="+MediaUrlId);
		String MediapageContent = murl.getText("utf-8")
		def thum = MediapageContent =~ REGEX_ITEMTHUMB
		assert thum.getCount() > 0, "Error : Page content not compatible"
		String thumblUrl = BaseUrl+thum[0][1]
		loginfo("MediaThumblUrl : "+thumblUrl)
		String MediaUrl = item.getAdditionalInfo()['ItemUrl']
		loginfo("MediaUrl       : "+MediaUrl);
		return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: MediaUrl, thumbnailUrl: thumblUrl)
	}

	private def get_json(String r){
		//Return the json-encode content of the String
		try {
			loginfo(String.format("JSON extract", r));
			def json = new JsonSlurper().parseText(r);
			return json;
		} catch (Exception e) {
			loginfo(String.format("JSON extract failed", r));
			return null;
		}
	}

	private String loginfo(String text) {
		log(text);
		println(text);
	}

	static WebResourceContainer testURL(String url, int itemCount = 2) {
		DisneyJunior extractor = new DisneyJunior();
		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.disney.fr/disney-junior/contenu/videos.jsp?b=mch",-1)
	}
}