package org.sillyjirafe.api;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.sillyblahaj.uoapi.element;

import com.sun.net.httpserver.HttpServer;

public class Start {
	public static void API(Connection conn) throws IOException {
	    HttpServer server = HttpServer.create(new InetSocketAddress(8081), 0);

	    server.createContext("/search", exchange -> {
	        String query = exchange.getRequestURI().getQuery();
	        Map<String, String> settings = parseQuery(query);

	        try {
	            List<element> results = Search.search(conn, settings);
	            String json = Json.JSONConvert(results);

	            exchange.getResponseHeaders().set("Content-Type", "application/json");
	            exchange.sendResponseHeaders(200, json.getBytes().length);
	            exchange.getResponseBody().write(json.getBytes());
	            exchange.getResponseBody().close();
	        } catch (Exception e) {
	            e.printStackTrace();
	            exchange.sendResponseHeaders(500, 0);
	            exchange.getResponseBody().close();
	        }
	    });

	    server.start();
	    System.out.println("Search API run on 8081 port");
	}
	
	public static Map<String, String> parseQuery(String query) {
	    Map<String, String> params = new HashMap<>();
	    
	    if (query == null) return params;
	    
	    String[] paires = query.split("&");
	    
	    for (String paire : paires) {
	        String[] cle_valeur = paire.split("=", 2);
	        if (cle_valeur.length == 2) {
	            params.put(cle_valeur[0], cle_valeur[1]);
	        }
	    }
	    
	    return params;
	}
}
