package code;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import db.DBC;
import db.Dominio;

public class StopHandler implements HttpHandler {

	@Override
	public void handle(HttpExchange he) throws IOException {

		URI requestedUri = he.getRequestURI();
		String requestMethod = he.getRequestMethod();

		String response = "ayyyyStoppo\n";

		// String requestMethod = he.getRequestMethod();
		String query = requestedUri.getRawQuery();
		String body = readBody(he.getRequestBody());
		// String response = "AYYYYY";
		String token=he.getRequestHeaders().get("Authorization").get(0).substring(7);
		String user = "";//he.getRequestHeaders().get("user").get(0);
		//verifica user keycloak
		
		
		try {
			//JSONObject tok=new JSONObject(token);
			//String accessToken=tok.getString("access_token");
			String[] tokSplit=token.split(".");
			if(tokSplit.length!=3)return;//controllo che il token abbia header,body e signature(abbia 2 punti :s)
			//int scnddot=accessToken.lastIndexOf(".");//dopo questo indice è tutta signature
			String signature=tokSplit[2];
			user=TokenHandler.verificaToken(token,signature);
		
			if(user.equals(""))return;
		
		
		} catch (NoSuchAlgorithmException | IOException | JSONException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		
		if (requestMethod.compareTo("POST") == 0 || requestMethod.compareTo("post") == 0) {

			String dominio = body.substring(7);
			System.out.println(
					requestMethod + "\n" + query + "\n" + body + "\n" + response + "\n" + user + "\n" + dominio + "\n");

			try {

//				Dominio d = DBC.getDom(dominio);
//				String s = user + "-A";
				
				
				ArrayList<String> ad= DBC.getDomainsAdmin(dominio);
				
				
				
				/*
				 * for(Dominio d : doms){ if( (d.getDomain() == dominio) &&
				 * d.getUsers().contains(s)) //something here
				 * System.out.println("OPERAZIONE NON IMPLEMENTATA");
				 * he.sendResponseHeaders(401,response.length()); OutputStream os =
				 * he.getResponseBody(); os.write("NON AUTORIZZATO".getBytes()); os.close();
				 * return; }
				 */
				if (!ad.contains(user)) {
					// he.sendResponseHeaders(401,0 );
					System.out.println("NON AUTORIZZATO");
					response = "NON AUTORIZZATO";
					he.sendResponseHeaders(401, response.length());
					OutputStream os = he.getResponseBody();

					os.write(response.getBytes());
					os.close();

					// System.out.println("OPERAZIONE NON IMPLEMENTATA");
					// he.sendResponseHeaders(501,0);
					// OutputStream os = he.getResponseBody();
					// os.write("OPERAZIONE NON IMPLEMENTATA".getBytes());
					// os.close();

					return;
				}

			} catch (SQLException|JSONException  e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			// effettuo chiamata a CloudAppManager
			// preso da https://www.baeldung.com/java-http-request

			// è una chiamata annidata nella risposta alla webapp
			// -richiesta REST da webApp a /install
			// -prendo da DB e poi chiamo CloudAppMng su /install
			// -attendo risposta da CloudAppMng e chiudo
			// -rispondo a webApp e chiudo
			// EZ

			//
			// standard per chiamata in slide
			// https://www.dir.uniupo.it/pluginfile.php/948883/mod_resource/content/1/FrameworkProgetto5.pdf
			//
			// http://127.0.0.1:8080/install
			URL url = new URL("http://127.0.0.1:3002/stop");// maybe, se CloudAppe è in localhost porta 8080
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("POST");
			con.setRequestProperty("Content-Type", "application/json");
			con.setRequestProperty("Accept", "application/json");

			//Map<String, String> parameters = new HashMap<>();

			// parameters.put("param1", "val");// fix parametri da mandare
			// leggo da DB domini e riempio (magari famo .DAO??)
			//parameters.put("domain", dominio);

			con.setDoOutput(true);
			DataOutputStream out = new DataOutputStream(con.getOutputStream());// inserimento param in call
			//out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
			out.writeBytes(dominio);
			out.flush();
			out.close();

			// con.setRequestProperty("Content-Type", "application/json");
			// String contentType = con.getHeaderField("Content-Type");

			con.setConnectTimeout(5000);
			con.setReadTimeout(5000);

			// leggo risposta
			int status = con.getResponseCode();

			Reader streamReader = null;

//			if (status > 299) {
//				System.out.println("pino5");
//				streamReader = new InputStreamReader(con.getErrorStream());
//				BufferedReader in = new BufferedReader(streamReader);
//				String inputLine;
//				StringBuffer content = new StringBuffer();
//				while ((inputLine = in.readLine()) != null) {
//					content.append(inputLine);
//				}
//				response = content.toString();
//				in.close();
//			} else {
//				System.out.println("pino6");
//				streamReader = new InputStreamReader(con.getInputStream());
//				BufferedReader in = new BufferedReader(streamReader);
//				String inputLine;
//				StringBuffer content = new StringBuffer();
//				while ((inputLine = in.readLine()) != null) {
//					content.append(inputLine);
//				}
//				response = content.toString();
//				in.close();
//			}
//			
//			BufferedReader in = new BufferedReader(
//					  new InputStreamReader(con.getInputStream()));
//			String inputLine;
//			StringBuffer content = new StringBuffer();
//			while ((inputLine = in.readLine()) != null) {
//					content.append(inputLine);
//					}
//			in.close();
//
//			con.disconnect();

			// finita chiamata a CloudApp

			// f.close();
			OutputStream os = he.getResponseBody();
			con.disconnect();
			he.sendResponseHeaders(status, response.length());// status
			os.write(response.getBytes());
			os.close();
		} 
//		else {
//			System.out.println("OPERAZIONE NON IMPLEMENTATA");
//			he.sendResponseHeaders(501, 0);
//			OutputStream os = he.getResponseBody();
//			os.write("OPERAZIONE NON IMPLEMENTATA".getBytes());
//			os.close();
//		}

	}

	private String readBody(InputStream requestBody) {
		int req;
		StringBuffer sb = new StringBuffer();
		try {
			while ((req = requestBody.read()) != -1)
				sb.append(Character.toString((char) req));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

}