/*
 * Copyright (c) 2009, syuu
 * License under the NicoCache License.
 */

package com.dokukino.genkidama;

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

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

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

public class DataServer {
	public void bind(int port) throws IOException {
        HttpHandler handler = new HttpHandler() {
			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() && !DHTManager.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();
                }
            }
        };
        
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext("/nc/", handler);
        server.start();
	}
}
