package org.positrium.waket.handler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.positrium.waket.AbstractDataServerHandler;
import org.positrium.waket.DataServerHandler;

import com.dokukino.genkidama.GenkidamaManager;
import com.sun.net.httpserver.HttpExchange;

import dareka.common.CloseUtil;
import dareka.processor.HttpHeader;
import dareka.processor.HttpUtil;
import dareka.processor.impl.Cache;

public class NicoCacheHandler extends AbstractDataServerHandler implements
		DataServerHandler {
	public static Log logger = LogFactory.getLog(NicoCacheHandler.class);
	
	@Override
	public String getUri() {
		return this.uri;
	}

	@Override
	public void handle(HttpExchange he) throws IOException {
		String cacheid = he.getRequestURI().getPath().replaceFirst("^/nc/", "");
		Cache cache = new Cache(cacheid, null);
		logger.info("cache requested: " + cacheid);
		if (cache.exists() && !GenkidamaManager.checkDeleted(cache.getId())) {
			logger.info("publishing cache: " + cache.getCacheFileName());
			he.getResponseHeaders().set(HttpHeader.CONTENT_TYPE, "video/flv");
			he.sendResponseHeaders(HttpURLConnection.HTTP_OK, cache.length());
			OutputStream out = he.getResponseBody();
			InputStream in = cache.getInputStream();
			try {
				HttpUtil.sendBody(out, in, cache.length());
			} finally {
				CloseUtil.close(out);
				CloseUtil.close(in);
			}
		} else {
			he.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, 0);
			he.getRequestBody().close();
		}
	}

}
