package code;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import org.json.JSONException;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpsExchange;
import com.sun.net.httpserver.HttpHandler;

import db.DBC;

public class PriviledgesHandler implements HttpHandler{

	public void handle(HttpExchange hex) throws IOException {
		HttpsExchange he = (HttpsExchange) hex;
		// String response = "{\"priviledges\":\"admin\"}" || "{\"priviledges\":\"user\"}";
		// check if the call is an options
		String requestMethod = he.getRequestMethod();
		if(requestMethod.compareToIgnoreCase("options") == 0) {
			Helper.sendCors(he, 200);
			return;
		}
		// exclude any request that isn't a get
		if(requestMethod.compareToIgnoreCase("get") != 0) {
			Helper.sendCors(he, 405);
			return;
		}
		// check if the user is logged in
		String user;
		if((user = Helper.checkTokenGetUser(he)) == null) {
			Helper.sendCors(he, 401);
			return;
		}
		// get the query
		String query = he.getRequestURI().getRawQuery();
		if(query == null) {
			Helper.sendCors(he, 400);
			return;
		}
		// parse the query
		Map<String, Object> parameters = Helper.parseQuery(query);
		// get the domain for which we want to know the priviledges
		String domain = (String) parameters.get("domain");
		// query the database
		try {
			ArrayList<String> adminlist = DBC.getDomainsAdmin(user);
			if(!adminlist.isEmpty() && adminlist.contains(domain)) {
				// the user is admin of this domain
				Helper.sendCors(he, 200, "{\"priviledges\":\"admin\"}");
				return;
			}
			ArrayList<String> userlist = DBC.getDomainsUser(user);
			if(!userlist.isEmpty() && userlist.contains(domain)) {
				// the user is user of this domain
				Helper.sendCors(he, 200, "{\"priviledges\":\"user\"}");
				return;
			}
		} catch (SQLException | JSONException e) {
			e.printStackTrace();
		}
		// the user is not admin or user of this domain
		Helper.sendCors(he, 404);
	}
}