package dareka.processor.impl;

import java.io.IOException;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import dareka.processor.HttpRequestHeader;
import dareka.processor.Processor;
import dareka.processor.Resource;
import dareka.processor.URLResourceCache;

// 外部サムネをメモリにキャッシュする
public class ExtThumbProcessor implements Processor {
	
	private static final String[] SUPPORTED_METHODS = new String[] { "GET" };
	private static final Pattern EXTTHUMB_URL_PATTERN = Pattern.compile(
			"^(http://(?:ext(?:|\\.seiga)|live)\\.nicovideo\\.jp/)" +
				"((?:thumb(?:|_[^/]+)|embed)/\\w{2}\\d+)(\\?\\w+)?$");
	
	private static final URLResourceCache resources =
		new URLResourceCache("cacheExtThumbMax", "cacheExtThumbExpire");
	
	public String[] getSupportedMethods() {
		return SUPPORTED_METHODS;
	}
	
	public Pattern getSupportedURLAsPattern() {
		return EXTTHUMB_URL_PATTERN;
	}
	
	public String getSupportedURLAsString() {
		return null;
	}
	
	protected void finalize() {
		// GCの時にでも全てのキャッシュをExpire処理してメモリを有効活用
		resources.expires();
	}
	
	public Resource onRequest(HttpRequestHeader requestHeader, Socket browser)
			throws IOException {
		String uri = requestHeader.getURI();
		Matcher m = EXTTHUMB_URL_PATTERN.matcher(uri);
		if (!m.matches()) {
			Resource.get(Resource.Type.URL, uri);
		}
		return resources.cacheAndRewrite(m.group(2), null, requestHeader);
	}
	
}
