/**
 * Copyright © 2012-2022 by Data Virtuality GmbH
 */
package org.teiid.auth.openid;


import org.teiid.logging.LogConstants;
import org.teiid.logging.LogManager;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * @author Archil Gabeskiria
 * @date 2022.08.01
 */
public class HttpClient {

    public static String get(String url) {
        return get(url, null);
    }

    public static String get(String url, Map<String, String> additionalHeaders) {
        HttpURLConnection http = null;
        try {
            http = (HttpURLConnection) new URL(url).openConnection();
            http.setRequestMethod("GET");
            if (additionalHeaders != null) {
                for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
                    http.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            return readResponse(http, url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (http != null) {
                http.disconnect();
            }
        }
    }

    public static String post(String url, String parameters, Map<String, String> additionalHeaders) {
        try {
            HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("charset", "utf-8");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setRequestProperty("Content-Length", "" + parameters.getBytes().length);
            if (additionalHeaders != null) {
                for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
                    http.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            http.setUseCaches(false);
            http.setDoInput(true);
            http.setDoOutput(true);
            try (DataOutputStream wr = new DataOutputStream(http.getOutputStream())) {
                wr.writeBytes(parameters);
            }
            return readResponse(http, url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String readResponse(HttpURLConnection http, String url) throws IOException {
        int responseCode = http.getResponseCode();
        boolean success = responseCode >= 200 && responseCode <= 299;
        if (!success) {
            LogManager.logError(LogConstants.CTX_CONNECTOR, String.format("Unsuccessful response code: %s, url: %s", responseCode, url));
            return null;
        }
        StringBuilder responseBuffer = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                responseBuffer.append(inputLine);
            }
        }
        return responseBuffer.toString();
    }
}