import org.serviio.library.online.ContentURLContainer;
import org.serviio.library.online.FeedItemUrlExtractor;
import org.serviio.library.online.PreferredQuality;


class ARDMediathek extends FeedItemUrlExtractor {

	final VALID_FEED_URL  = '^http://www.ardmediathek.de/ard/servlet/export/rss/id=.*$'
	final VALID_THUMB_URL = '.*setPreviewImage(.*).*'
	final VALID_VIDEO_URL = '.*mediaCollection.addMediaStream.*'
	
	private print(Object msg) 
	{
		log(msg)
	}
	
	@Override
	public String getExtractorName() {
		return "ARD Mediathek RSS Extractor"
	}
	
	boolean extractorMatches(URL feedUrl) {
		 return feedUrl ==~ VALID_FEED_URL
	}
	
	protected ContentURLContainer extractUrl(Map links, PreferredQuality quality) {
		def linkUrl = links.alternate != null ? links.alternate : links.default
		def webPage = linkUrl.getText()
	
		this.print("Parsing: " + linkUrl)
		
		//preview image
		//setPreviewImage("/ard/servlet/contentblob/93/64/52/80/9364528/bild/323881");
		def ThumbnailUrl = null
		def matcher1 = webPage =~ VALID_THUMB_URL
		if (matcher1 != null)
		{
			def linkParts1 = matcher1[0].toString().split('"')
		    ThumbnailUrl = "http://www.ardmediathek.de" + linkParts1[3].toString()
			this.print("  - Thumbnail: " + ThumbnailUrl)
		}
		
		//extract video
		def video = null
		def matcher2 = webPage =~ VALID_VIDEO_URL
		if (matcher2 != null)
		{
			def index = 0
			if (quality == PreferredQuality.HIGH)
			{
				index = 2;
			}
			else if (quality == PreferredQuality.MEDIUM)
			{
				index = 1;
			}
			else
			{
				index = 0;
			}
			
			def linkParts1 = matcher2[index].toString().split('"')
			video = linkParts1[1].toString() + linkParts1[3].toString()
			video = video.replace("mp4:videoportal/", "videoportal/mp4:")
			this.print("  - Video: " + video)
		}
		
		return new ContentURLContainer(contentUrl: video, thumbnailUrl: ThumbnailUrl)
	}
	
	// for testing
	public static void main(String[] args) {
		String testUrl = "http://www.ardmediathek.de/ard/servlet/export/rss/id=9176820";
		
		ARDMediathek ard = new ARDMediathek();
		assert ard.extractorMatches(new URL(testUrl))
		
		Map links = ['alternate': new URL("http://www.ardmediathek.de/ard/servlet/content/3517136?documentId=9364516")]
		ContentURLContainer result = ard.extractUrl(links, PreferredQuality.MEDIUM)
	}
}
