package com.vc.servlets;

import com.vc.util.VCAuthUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.http.*;
import javax.servlet.*;

/**
 * Created by cmparish on 3/26/17.
 */
public class RedirectServlet extends HttpServlet {

    private static String VC_URI = "https://api.vivialconnect.net";
    public void init() throws ServletException
    {
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        process(request, response);
    }

    public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        process(request, response);
    }

    public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        process(request, response);
    }


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        process(request, response);

    }

    public void destroy()
    {
        // do nothing.
    }


    protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Actual logic goes here.
        PrintWriter out = response.getWriter();

        String pathInfo = request.getPathInfo();
        String queryString = request.getQueryString();
        String requestType = request.getMethod();
        String publicKey = request.getHeader("publicKey");
        String secretKey = request.getHeader("secretKey");

        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        String requestBody = buffer.toString();


        if (requestBody == null ) {requestBody = ""; }

        String vcRequestURI = VC_URI + pathInfo;
        if(queryString != null && queryString.length() > 0) {
            vcRequestURI += "?" + queryString;
        }

        Date date = new Date();
        URI uri = null;

        try {
            uri = new URI(vcRequestURI);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        // Set response content type
        response.setContentType("text/html");
        String output = sendHTTPMessage(uri, requestType, publicKey, secretKey, requestBody, date);
        out.println(output);

    }
    
    protected String sendHTTPMessage(URI uri, String requestMethodType, String publicKey, String secretKey, String jsonData, Date date) throws IOException{


        HttpURLConnection connection = null;
        VCAuthUtil util = new VCAuthUtil(publicKey, secretKey);

        try {
            //Create connection
            URL url = new URL(uri.toString());
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(requestMethodType);
            HashMap<String, String> authMap = util.generateAuthorization(uri, requestMethodType, jsonData, date);

            Iterator it = authMap.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next().toString();
                connection.setRequestProperty(key, authMap.get(key));
            }
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");

            connection.setUseCaches(false);

            if ("POST".equals(requestMethodType)) {
                connection.setDoOutput(true);

                //Send request
                DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
                wr.writeBytes(jsonData);
                wr.close();
            }
            //Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            StringBuffer response = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\n');
            }
            rd.close();


            return response.toString();
        } catch (IOException io) {
            io.printStackTrace();
            throw io;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

    }
    
}

@@ -1383,43 +1383,8 @@
  %7B%0A%0A
-        // Actual logic goes here.%0A
     
@@ -1427,16 +1427,92 @@
 iter();%0A
+        %0A        //Get info needed to make direct API call on the vc service
 %0A       
@@ -1773,24 +1773,86 @@
 cretKey%22);%0A%0A
+        %0A        //this gets the request body (blank for GET)%0A
         Stri
@@ -2113,65 +2113,207 @@
 ();%0A
-%0A%0A        if (requestBody == null ) %7BrequestBody = %22%22; %7D%0A
+        //TODO - this may not be necessary, the body sould never be null;%0A        if (requestBody == null ) %7BrequestBody = %22%22; %7D%0A           %0A        //generate the endpoint to the connect web service
 %0A   
@@ -2473,24 +2473,32 @@
 ;%0A        %7D%0A
+        
 %0A        Dat
@@ -2542,17 +2542,16 @@
 = null;%0A
-%0A
         
@@ -2760,24 +2760,94 @@
 ext/html%22);%0A
+        %0A        //method to make all to API and return the response.%0A
         Stri
@@ -3131,18 +3131,16 @@
 eption%7B%0A
-%0A%0A
         

Update RedirectServlet.java