package gmt.io.rest;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import gmt.common.type.LogLevelType;
import gmt.io.rest.event.GmtHttpHandler;
import gmt.logger.GmtLogManager;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Iterator;

public class GmtRESTServer {
	private InetSocketAddress addr;
	private HttpServer server;
	private HashMap<String, GmtHttpHandler> handlerMap;
    private GmtLogManager logger;
	private String ip;
	private int port;
	
	

	public GmtRESTServer(String address, int port) {
		try {
			logger = GmtLogManager.getInstance();
			
			this.ip = address;
			this.port = port;

			handlerMap = new HashMap<String, GmtHttpHandler>();
			InetSocketAddress addr = new InetSocketAddress(address, port);
			server = HttpServer.create(addr, 0);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void addContext(String uri, GmtHttpHandler handler) {
		if (handlerMap != null && !uri.equals("") && handler != null) {
			handlerMap.put(uri, handler);
		}
	}

	public void creatContext() {
		Iterator<String> it = handlerMap.keySet().iterator();

		while (it.hasNext()) {
			String key = (String) it.next();
			HttpContext context = server.createContext(key);
			context.setHandler(handlerMap.get(key));
		}
	}

	public void start() {
		if (server != null) {
			server.setExecutor(null); // creates a default executor
			server.start();
			
			logger.writeLevelLog("[REST SERVER] START -- IP : " + ip + " | " + "Port : " + port + "--", LogLevelType.LOG_INFO, "AllLog" );

		}
	}

}