package it.richkmeli.RMS.web.util;

import it.richkmeli.RMS.web.response.KOResponse;
import it.richkmeli.RMS.web.response.OKResponse;
import it.richkmeli.RMS.web.response.StatusCode;
import it.richkmeli.jcrypto.KeyExchangePayloadCompat;
import it.richkmeli.jframework.database.DatabaseException;
import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet({"/command"})
public class command extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter out = resp.getWriter();
        HttpSession httpSession = req.getSession();
        Session session = null;

        try {

            BufferedReader br = req.getReader();
            String response = br.readLine();

//            session = ServletManager.getServerSession(httpSession);
//
//            JSONObject JSONData = new JSONObject(response);
//            String deviceName = JSONData.getString("data0");
//            String requestor = JSONData.getString("data1");
//
//            System.out.println(deviceName + " " + requestor);
//
//            if (deviceName != null && requestor != null) {
//                String output = null;
//
//                if (requestor.equalsIgnoreCase("agent")) {
//                    output = session.getDeviceDatabaseManager().getCommands(deviceName);
//                } else if (requestor.equalsIgnoreCase("client")) {
//                    output = session.getDeviceDatabaseManager().getCommandsOutput(deviceName);
//                    session.getDeviceDatabaseManager().setCommandsOutput(deviceName, "");
//                }
//
//                if (!output.isEmpty()) {
//                    out.println((new OKResponse(StatusCode.SUCCESS, output)).json());
//                } else {
//                    out.println((new KOResponse(StatusCode.FIELD_EMPTY)).json());
//                }
//            }
//
//            br.close();

            session = ServletManager.getServerSession(httpSession);

            if (req.getParameterMap().containsKey("data0") && req.getParameterMap().containsKey("data1")) {

                String deviceName = req.getParameter("data0");
                String requestor = req.getParameter("data1");

                String output = null;

                if (requestor.equalsIgnoreCase("agent")) {
                    output = session.getDeviceDatabaseManager().getCommands(deviceName);
                } else if (requestor.equalsIgnoreCase("client")) {
                    output = session.getDeviceDatabaseManager().getCommandsOutput(deviceName);
                    session.getDeviceDatabaseManager().setCommandsOutput(deviceName, "");
                }

                if (!output.isEmpty()) {
                    out.println((new OKResponse(StatusCode.SUCCESS, output)).json());
                } else {
                    out.println((new KOResponse(StatusCode.FIELD_EMPTY)).json());
                }

            } else {
                out.println((new KOResponse(StatusCode.GENERIC_ERROR, "Parameters missing")).json());
            }
        } catch (it.richkmeli.RMS.web.util.ServletException | DatabaseException e/* | CryptoException e*/) {
            out.println((new KOResponse(StatusCode.GENERIC_ERROR, e.getMessage())).json());
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //TODO: gestire richieste per multipli device

        PrintWriter out = resp.getWriter();
        HttpSession httpSession = req.getSession();
        Session session = null;

        try {
            BufferedReader br = req.getReader();
            String data = br.readLine();
            JSONObject JSONData = new JSONObject(data);
            String deviceName = JSONData.getString("device");
            String commands = JSONData.getString("commands");

            session = ServletManager.getServerSession(httpSession);

            if (session.getDeviceDatabaseManager().editCommands(deviceName, commands))
                out.println((new OKResponse(StatusCode.SUCCESS)).json());
            else
                out.println((new KOResponse(StatusCode.FIELD_EMPTY)).json());
            br.close();
        } catch (it.richkmeli.RMS.web.util.ServletException | JSONException | DatabaseException e/* | CryptoException e*/) {
            out.println((new KOResponse(StatusCode.GENERIC_ERROR, e.getMessage())).json());
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter out = resp.getWriter();
        HttpSession httpSession = req.getSession();
        Session session = null;

        try {
            BufferedReader br = req.getReader();
            String response = br.readLine();

            JSONObject JSONData = new JSONObject(response);
            String deviceName = JSONData.getString("device");
            String commandsOutput = JSONData.getString("data");

            session = ServletManager.getServerSession(httpSession);

            session.getDeviceDatabaseManager().setCommandsOutput(deviceName, commandsOutput);
            session.getDeviceDatabaseManager().editCommands(deviceName, "");

            out.println((new OKResponse(StatusCode.SUCCESS)).json());
            br.close();
        } catch (it.richkmeli.RMS.web.util.ServletException | JSONException | DatabaseException e/* | CryptoException e*/) {
            out.println((new KOResponse(StatusCode.GENERIC_ERROR, e.getMessage())).json());
        }
    }

    //TODO: fare metodo per gestire la richiesta degli output da client -> modificare anche webapp

    private String GenerateKeyExchangePayloadJSON(KeyExchangePayloadCompat keyExchangePayload) {
        String keyExchangePayloadJSON;// = "[ ";
        keyExchangePayloadJSON = /*"'" + index + "' : {"*/ "{"
                + "'encryptedAESsecretKey' : '" + keyExchangePayload.getEncryptedAESsecretKey() + "', "
                + "'signatureAESsecretKey' : '" + keyExchangePayload.getSignatureAESsecretKey() + "', "
                + "'kpubServer' : '" + keyExchangePayload.getKpubServer() + "', "
                + "'data' : '" + keyExchangePayload.getData() + "'}";
        //keyExchangePayloadJSON += " ]";
        return keyExchangePayloadJSON;
    }
}

@@ -281,32 +281,59 @@
 abaseException;%0A
+import org.json.JSONArray;%0A
 import org.json.
@@ -677,16 +677,36 @@
 tWriter;
+%0Aimport java.util.*;
 %0A%0A@WebSe
@@ -4125,37 +4125,41 @@
             
-String
+JSONArray
  device
+s
 Name = JSOND
@@ -4161,38 +4161,41 @@
 JSONData.get
-String
+JSONArray
 (%22device
 %22);%0A        
@@ -4174,32 +4174,33 @@
 SONArray(%22device
+s
 %22);%0A            
@@ -4331,20 +4331,134 @@
         
-if (
+List%3CString%3E failedResponse = new ArrayList%3C%3E();%0A            for (Object device : devicesName) %7B%0A                if (!
 session.
@@ -4497,26 +4497,31 @@
 ommands(
+(String) 
 device
-Name
 , comman
@@ -4524,16 +4524,150 @@
 mmands))
+ %7B%0A                    failedResponse.add((String) device);%0A                %7D%0A            %7D%0A%0A            if (failedResponse.isEmpty())
 %0A       
@@ -4749,16 +4749,18 @@
     else
+ %7B
 %0A       
@@ -4814,35 +4814,93 @@
 .FIELD_EMPTY
-)).json());
+, Arrays.toString(failedResponse.toArray()))).json());%0A            %7D%0A
 %0A           

Update doPud