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.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
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.HttpHandler;

import db.DBC;
import db.Dominio;
import io.fusionauth.jwt.Verifier;
import io.fusionauth.jwt.domain.JWT;
import io.fusionauth.jwt.ec.ECVerifier;


public class ServicesHandler implements HttpHandler{
	
	
	public void handle(HttpExchange he) throws IOException {

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

		String response = "";

		String query = requestedUri.getRawQuery();
		String body = readBody(he.getRequestBody());
		String user="";
		Map<String, Object> parameters = new HashMap<String, Object>();
		parseQuery(query, parameters);
		String domain=(String) parameters.get("domain");
		// String user = he.getRequestHeaders().get("user").get(0);
		String token = he.getRequestHeaders().get("Authorization").get(0).substring(7);// taglio bearer
		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.compareToIgnoreCase("GET") == 0) {
			
			
			JSONObject res = new JSONObject();
			JSONArray rs =null;

			//ArrayList<String> modulesList;
			try {
				//modulesList = DBC.getModules();

				//for (String k : modulesList) {
				//	rs.put(k);
				rs= DBC.getServices(domain);
				res.put("response", rs);

			} catch (SQLException | JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			int status = 200;

			OutputStream os = he.getResponseBody();
			he.sendResponseHeaders(status, res.length());
			os.write(res.toString().getBytes());
			// he.sendResponseHeaders(status, response.length());//status
			// os.write(response.getBytes());
			os.close();

			// JSONObject j=new JSONObject();
			// j.append("User", DBC.getDomainsUser(user));

			// j=(""+":"+);

		}

	}
	
	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();
	}
	
	
	void parseQuery(String query, Map<String, Object> parameters) throws UnsupportedEncodingException {

		if (query != null) {
			String pairs[] = query.split("[&]");
			for (String pair : pairs) {
				String param[] = pair.split("[=]");
				String key = null;
				String value = null;
				if (param.length > 0) {
					key = URLDecoder.decode(param[0], System.getProperty("file.encoding"));
				}

				if (param.length > 1) {
					value = URLDecoder.decode(param[1], System.getProperty("file.encoding"));
				}

				if (parameters.containsKey(key)) {
					Object obj = parameters.get(key);
					if (obj instanceof List<?>) {
						List<String> values = (List<String>) obj;
						values.add(value);

					} else if (obj instanceof String) {
						List<String> values = new ArrayList<String>();
						values.add((String) obj);
						values.add(value);
						parameters.put(key, values);
					}
				} else {
					parameters.put(key, value);
				}
			}
		}
	}

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}