package code;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.sql.SQLException;

import com.sun.net.httpserver.HttpServer;

import db.Connect;
import db.DBC;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

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

public class Domain {
	
	static public int port=3001;

	public static void main(String[] args) throws IOException, JSONException {
		if(args.length>1 && args[0].equals("-port")) try {
			port = Integer.parseInt(args[1]);
		}
		
		catch (Exception e) {
			e.printStackTrace();
		}
		ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)Executors.newCachedThreadPool();////newFixedThreadPool(5)
		HttpServer server=HttpServer.create(new InetSocketAddress(port),0);
		
		//Connect.connect();
		
		
		//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();
		// 3000/install da inserire
		con.setRequestMethod("GET");
		con.setRequestProperty("Content-Type", "application/json");
		con.setRequestProperty("Accept", "application/json");
		con.setDoOutput(true);
		con.setConnectTimeout(5000);
		con.setReadTimeout(5000);
		
//		DataOutputStream out = new DataOutputStream(con.getOutputStream());// inserimento param in call
//		out.writeBytes(j.toString());// ParameterStringBuilder.getParamsString(parameters));
//		out.flush();
//		out.close();

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

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

		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();
		
//		System.out.println(content);
		//manipolazione per ottenere i campi dei moduli
		JSONObject obj=new JSONObject(content.toString());
//		System.out.println(obj.toString());
		//String s=content.toString();
		//ArrayList<String>arr=s.
		
		//String []s1=s.split(",");
		JSONArray jr = obj.getJSONArray("response"); 
		
		//String []s1=(String[]) obj.get("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++)
//			System.out.println(s1[i]);
//		
		//ArrayList<String> arr= new ArrayList<String>();
		for(int i=0;i<s1.length;i++) {
			String remZip=s1[i].substring(0, s1[i].length()-4);
//			System.out.println("remmZip = "+remZip);
			//arr.add(s1[i]);
			//String[] curr=s1[i].split("-");
			String[] curr=remZip.split("-");
			for(int j=0;j<curr.length;j++) {
//				System.out.println("curr["+j+"] = "+curr[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) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else {
					String a=curr[0];
					try {
						//inserimento modulo arduino
						DBC.fillModules(a,"Arduino1", s1[i]);
					} catch (SQLException | JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					}
			}
		}
		
				
		server.setExecutor(threadPoolExecutor);
		System.out.println("Domain in ascolto\n");
		
		//server.createContext("/", new RootHandler(port));
		//server.createContext("/index", new IndexHandler());
		//install-start-stop-delete
		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.start();
	}

}