package org.positrium.waket.proxy;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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

/**
 * NicoCache Proxyを使って、http://genkidama.dokukino.com/local/(.+)にアクセスすると、<br>
 * http://localhost:(dhtDataPort)/$1 へ接続するようになる。
 * 
 * @author token , 2009 CC BY-SA
 * @version $Rev: 131 $
 * 
 * 
 * 
 */
public class WaketProcessor implements Processor {
	public static Log logger = LogFactory.getLog(WaketProcessor.class);

	private static final String[] SUPPORTED_METHODS = new String[] {
			HttpHeader.GET, HttpHeader.POST, HttpHeader.HEAD };

	// check regext : http://www.fileformat.info/tool/regex.htm
	private final static Pattern WAKET_URL_PATTERN = Pattern
			.compile("^http://genkidama\\.us/local/(.+)");

	/*
	 * (non-Javadoc)
	 * 
	 * @see dareka.processor.Processor#getSupportedMethods()
	 */
	@Override
	public String[] getSupportedMethods() {
		return SUPPORTED_METHODS;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see dareka.processor.Processor#getSupportedURLAsPattern()
	 */
	@Override
	public Pattern getSupportedURLAsPattern() {
		return WAKET_URL_PATTERN;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see dareka.processor.Processor#getSupportedURLAsString()
	 */
	@Override
	public String getSupportedURLAsString() {
		return null;
	}

	/**
	 * <code>http://localhost:50001/$1</code>へ接続させる
	 * 
	 * @see dareka.processor.Processor#onRequest(dareka.processor.HttpRequestHeader)
	 */
	@Override
	public Resource onRequest(HttpRequestHeader requestHeader)
			throws IOException {
		logger.debug("original: " + requestHeader.getURI());
		Matcher m = WAKET_URL_PATTERN.matcher(requestHeader.getURI());

		String url = "http://localhost:" + Integer.getInteger("dhtDataPort")
				+ "/";
		if (m.matches()) {
			url += m.group(1);
			logger.debug("replaced: " + url);
		}

		Resource r = Resource.get(Resource.Type.URL, url);
		return r;
	}

}
