package code;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.sql.SQLException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

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

import com.sun.net.httpserver.HttpServer;

import db.DBC;

public class Domain {

	static public int port=3001;

	public static void main(String[] args) throws IOException, JSONException {
		
		ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)Executors.newCachedThreadPool();
		HttpServer server=HttpServer.create(new InetSocketAddress(port),0);

		//chiamata per popolare moduli

		URL url = new URL("https://gitlab.di.unipmn.it/alfredo/iotlabgw.edu-al.unipmn.it/-/raw/main/index.json");
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
	
		Helper.setConnectionSettings(con,"GET");

		// leggo risposta
		int status = con.getResponseCode();
		//controllare ToDo
		String content = Helper.getResponseFromConnection(con);
		con.disconnect();

		//manipolazione per ottenere i campi dei moduli
		riempiModuli(content);

		server.setExecutor(threadPoolExecutor);

		server.createContext("/install/", new InstallHandler());
		server.createContext("/start/", new StartHandler());
		server.createContext("/stop/", new StopHandler());
		server.createContext("/delete/", new DeleteHandler());
		server.createContext("/secured/domains/", new TokenHandler());
		server.createContext("/secured/services", new ServicesHandler());
		server.createContext("/secured/priviledges", new PriviledgesHandler());

		server.start();
		System.out.println("Domain in ascolto su "+Helper.getSelfURL());
	}
	
	private static void riempiModuli(String content) throws JSONException {
		
		JSONObject obj=new JSONObject(content);
		JSONArray jr = obj.getJSONArray("response");
		String []s1=new String[jr.length()];

		for(int i=0;i<jr.length();i++) {
			s1[i]=jr.getString(i);
		}
		for(int i=0;i<s1.length;i++) {
			String remZip=s1[i].substring(0, s1[i].length()-4);
			String[] curr=remZip.split("-");
			for(int j=0;j<curr.length;j++) {
				if(curr.length>1) {
					String a=curr[0];
					String b=curr[1];
					try {
						//inserimento modulo non arduino
						DBC.fillModules(a, b, s1[i]);
					} catch (SQLException | JSONException e) {
						e.printStackTrace();
					}
				}
				else {
					String a=curr[0];
					try {
						//inserimento modulo arduino
						DBC.fillModules(a,"Arduino1", s1[i]);
					} catch (SQLException | JSONException e) {
						e.printStackTrace();
					}

				}
			}
		}
	}

}