package nl.ovpay.queue;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class Helpers {

    private static Logger LOGGER = LoggerFactory.getLogger(Helpers.class);

    public static String getAlertId(String string) throws IOException {
        return new JSONObject(string).get("alertId").toString();
    }

    public static String getTripId(String string) throws IOException {
        return new JSONObject(string).get("tripId").toString();
    }

    public static String getXbot(String string) throws IOException {
        return new JSONObject(string).get("xbot").toString();
    }

    public static void getTripDetails(String tripId, String xbot, String gboBearerToken) throws Exception {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, DummyX509TrustManager.getDummyArray(), new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        URL url = new URL("https://api.sbx.idbt.translink.nl/api/v3/id-media/tokens/xbot/" + xbot + "/trips/details/" + tripId);
        URLConnection con = url.openConnection();
        HttpURLConnection http = (HttpURLConnection)con;
        http.setRequestMethod("GET");
        http.setDoOutput(true);
        http.setRequestProperty("Authorization", "Bearer " + gboBearerToken);
        http.connect();

        try(InputStream is = http.getInputStream()) {
            String response = new String(is.readAllBytes(), StandardCharsets.UTF_8);
            LOGGER.info("GBO API 8659 trip details response for xBOT " + xbot + " and tripId " + tripId + ": \n" + new JSONObject(response).toString(2));
        }
    }

    public static void getAlertDetails(String alertId, String xBot, String gboBearerToken) throws Exception {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, DummyX509TrustManager.getDummyArray(), new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());


        URL url = new URL("https://api.sbx.idbt.translink.nl/api/v3/id-media/tokens/xbot/" + xBot + "/alerts/" + alertId + "/details");
        URLConnection con = url.openConnection();
        HttpURLConnection http = (HttpURLConnection)con;
        http.setRequestMethod("GET");
        http.setDoOutput(true);
        http.setRequestProperty("Authorization", "Bearer " + gboBearerToken);
        http.connect();

        try(InputStream is = http.getInputStream()) {
            String response = new String(is.readAllBytes(), StandardCharsets.UTF_8);
            LOGGER.info("GBO API 8851 alert details response for xBOT " + xBot + " and alertId " + alertId + ": \n" + new JSONObject(response).toString(2));
        }
    }

    public static String getGboBearerToken() throws IOException, NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, DummyX509TrustManager.getDummyArray(), new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        URL url = new URL("https://api.sbx.idbt.translink.nl/api/v3/auth/oauth2/token");
        URLConnection con = url.openConnection();
        HttpURLConnection http = (HttpURLConnection)con;
        http.setRequestMethod("POST");
        http.setDoOutput(true);

        Map<String,String> arguments = new HashMap<>();
        arguments.put("client_id", "HTM-auth-client");
        arguments.put("client_secret", "HTM-auth-827kJJ");
        arguments.put("grant_type", "client_credentials");
        StringJoiner sj = new StringJoiner("&");
        for(Map.Entry<String,String> entry : arguments.entrySet())
            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
                   + URLEncoder.encode(entry.getValue(), "UTF-8"));
        byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
        int length = out.length;

        http.setFixedLengthStreamingMode(length);
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        http.connect();
        try(OutputStream os = http.getOutputStream()) {
            os.write(out);
        }
        try(InputStream is = http.getInputStream()) {
            String response = new String(is.readAllBytes(), StandardCharsets.UTF_8);
            JSONObject json = new JSONObject(response);
            LOGGER.info("Got GBO bearer token: " + json.get("access_token"));
            return json.get("access_token").toString();
        }
    }
}
