package code;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.net.ssl.HttpsURLConnection;

import org.json.JSONException;
import org.json.JSONObject;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpsExchange;
import java.net.HttpURLConnection;

import db.DBC;

public class StopHandler implements HttpHandler {

	@Override
	public void handle(HttpExchange hex) throws IOException {
		HttpsExchange he = (HttpsExchange) hex;

		String requestMethod = he.getRequestMethod();

		if (requestMethod.compareToIgnoreCase("options") == 0) {
			Helper.sendCors(he, 200);
			return;
		}
		if (requestMethod.compareToIgnoreCase("POST") != 0) {
			Helper.sendCors(he, 405);
			return;
		}

		String body = Helper.readBody(he.getRequestBody());
		String user= Helper.checkTokenGetUser(he);

		if (user == null) {
			Helper.sendCors(he, 401);
			return;
		}
		String domain;
		try {
			domain = new JSONObject(body).getString("domain");

			ArrayList<String> ad = DBC.getDomainsAdmin(user);

			if (!ad.contains(domain)) {
				Helper.sendCors(he, 401);
				return;
			}

		} catch (SQLException | JSONException e) {
			e.printStackTrace();
			return;
		}

		HttpURLConnection con = Helper.sendMessageToCloudapp("stop", body);
		int status = con.getResponseCode();
		// FIXME serve avere anche il content?
		// String cloudappResponse = Helper.getResponseFromConnection(con);
		con.disconnect();

		Helper.sendCors(he, status);
		DBC.setStatoDomain(domain, 0);
	}
}