package com.studiogibbs.serviio;

import java.util.regex.Matcher;
import org.serviio.library.online.*;

class TumblrFeedExtractor extends org.serviio.library.online.WebResourceUrlExtractor {

	boolean extractorMatches(URL feedUrl) {
		log("Checking: " + feedUrl.toExternalForm());
		boolean result = feedUrl.toExternalForm() ==~ "(http\\://)?[0-9A-Za-z\\-]+\\.tumblr\\.com/?";
		log("Result: " + result);
		return result;
	}

	String getExtractorName() {
		return "TumblrExtractor";
	}

	int getVersion() {
		return 0;
	}

	int getExtractItemsTimeout() {
		return 60;
	}

	WebResourceContainer extractItems(URL tumblrUrl, int maxItems) {
		log("extractItems: " + tumblrUrl + " : " + maxItems);

		int toFetch = maxItems;
		if (maxItems < 0 || maxItems > 50) {
			maxItems = 50;
		}

		WebResourceContainer result = new WebResourceContainer();
		List<WebResourceItem> items = new LinkedList<WebResourceItem>();

		result.setItems(items);

		long fetched = 0;
		while (fetched < toFetch || toFetch < 0) {
			log("fetching posts " + fetched + "-" + (fetched + maxItems) + " for " + tumblrUrl);

			String path = (tumblrUrl.toExternalForm().endsWith("/") ? "" : "/") + "api/read?type=photo&num=" + maxItems + "&start=" + fetched;

			URL feedURL = new URL(tumblrUrl.toExternalForm() + path);

			def feed = new XmlSlurper().parseText(openURL(feedURL, ""));
			if (toFetch < 0) {
				toFetch = Long.parseLong(feed.posts[0].@total.text());
				log("extracting " + toFetch + " items for " + tumblrUrl);
			}
		
			result.setTitle(feed.tumblelog[0].@title.text());

			feed.posts[0].post.list().each() {
	                        def post = it;
				String postTitle = post.@id.text();
				if (post.@slug.text() != "") {
	                		postTitle = post.@slug.text();
				}
				long ts = Long.parseLong(post['@unix-timestamp'].text());
				Date relDate = new Date(ts * 1000);

				if (post.photoset[0]) {
					post.photoset[0].photo.list().each() {
	                                        def photo = it;
						WebResourceItem item = new WebResourceItem();
						if (photo.@caption.text() != "") {
							item.setTitle(photo.@caption.text());
						} else {
							item.setTitle(postTitle + "-" + photo.@offset.text());
						}
				
						item.setReleaseDate(relDate);
						Map<String,String> addInfo = new HashMap<String,String>();
						photo['photo-url'].list().each() {
							addInfo[it['@max-width'].text()] = it.text();
						}
						item.setAdditionalInfo(addInfo);
						item.setCacheKey(post.@id.text() + "-" + photo.@offset.text());
						items.add(item);
					}
				} else {
					WebResourceItem item = new WebResourceItem();
					item.setTitle(postTitle);
			
					item.setReleaseDate(relDate);
					Map<String,String> addInfo = new HashMap<String,String>();
					post['photo-url'].list().each() {
						addInfo[it['@max-width'].text()] = it.text();
					}
					item.setAdditionalInfo(addInfo);
					item.setCacheKey(post.@id.text());
					items.add(item);
				}
			
				fetched += 1;
			}
		} 

		return result;
	}

	ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {
		log("extractUrl: " + item.getAdditionalInfo()["75"] + " : " + requestedQuality);
		String size = "";

		switch (requestedQuality) {
			case PreferredQuality.LOW: size = "250";
				break;
			case PreferredQuality.MEDIUM: size = "500";
				break;
			case PreferredQuality.HIGH:
			default:
				size = "1280";
		}
		ContentURLContainer result = new ContentURLContainer();

		result.setContentUrl(item.getAdditionalInfo()[size]);
		result.setThumbnailUrl(item.getAdditionalInfo()["75"]);
		result.setFileType(org.serviio.library.metadata.MediaFileType.IMAGE);
		result.setCacheKey(item.getCacheKey() + "-" + size);
		
		log("extracted: " + result);

		return result;
	}

}