package code;

import java.io.IOException;
import java.net.URI;
import java.sql.SQLException;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpsExchange;
import com.sun.net.httpserver.HttpHandler;
import db.DBC;

public class ServicesHandler implements HttpHandler{


	public void handle(HttpExchange hex) throws IOException {
		HttpsExchange he = (HttpsExchange) hex;
		URI requestedUri = he.getRequestURI();
		String requestMethod = he.getRequestMethod();

		if (requestMethod.compareToIgnoreCase("options") == 0) {
			Helper.sendCors(he, 200);
			return;
		}
		if (requestMethod.compareToIgnoreCase("GET") != 0) {
			Helper.sendCors(he, 405);
			return;
		}
		if(Helper.checkTokenGetUser(he) == null) {
			Helper.sendCors(he, 401);
			return;
		}
		String response = "";
		// get the query (if any)
		String query = requestedUri.getRawQuery();
		String domain = null;
		if(query != null){
			Map<String, Object> parameters = Helper.parseQuery(requestedUri.getRawQuery());
			domain=(String) parameters.get("domain");
		}
		JSONObject res = new JSONObject();
		if(domain != null){
			// I have to send only the services used by this domain
			JSONArray rs =null;
			try {
				rs= DBC.getServicesInUseByDomain(domain);
				res.put("response", rs);
			} catch (SQLException | JSONException e) {
				e.printStackTrace();
			}
		} else {
			// I have to send all available services
			JSONArray rs = DBC.getAllServices();
			try {
				res.put("response",rs);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		response = res.toString();
		// questa parte sopra serve anche qui, non solo quando si chiama con OPTIONS
		Helper.sendCors(he, 200, response);
	}
}