/**
 * Copyright © 2012-2022 by Data Virtuality GmbH
 */
package org.teiid.resource.adapter.ws;

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

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipException;

/**
 * @author Adil Hamiani
 * @date 2022.08.09
 */
public class HttpUtils {
    private HttpUtils() {
    }

    public static InputStream getInputStream(boolean failedOnHttpError, boolean decompressCompressedFiles, int httpCode, String responseMessage,
                                             InputStream errorStream, InputStream inputStream, StringBuilder errMsg) throws IOException {
        if (failedOnHttpError && httpCode >= 400) {
            // END EXTENSION
            errMsg.append(" [*HTTP Response: ");
            errMsg.append(httpCode);
            errMsg.append(" ");
            errMsg.append(responseMessage);
            errMsg.append("*]");
            errMsg.append("** http error stream **");
            if (errorStream != null) {
                BufferedReader rd = new BufferedReader(new InputStreamReader(errorStream));
                String line;
                while ((line = rd.readLine()) != null) {
                    errMsg.append("*");
                    errMsg.append(line);
                }
                rd.close();
            }
            LogManager.logError(LogConstants.CTX_CONNECTOR, "Error executing http request " + errMsg.toString());
        }

        if (decompressCompressedFiles) {
            InputStream in;
            try {
                in = new GZIPInputStream(inputStream);
            } catch (ZipException e) {
                in = inputStream;
            }
            return in;
        }
        return inputStream;
    }

    public static InputStream handleError(InputStream inputStream, StringBuilder errMsg) {
        if (inputStream != null) {
            return inputStream;
        } else if (errMsg != null && errMsg.length() > 0) {
            return new ByteArrayInputStream(errMsg.toString().getBytes());
        }

        // return just empty InputStream
        return new InputStream() {
            @Override
            public int read() throws IOException {
                return -1;
            }
        };
    }

    public static void logException(int httpCode, String message, boolean failOnHttpError) throws IOException {
        StringBuilder errMsg;
        errMsg = new StringBuilder();
        errMsg.append("** http error stream **");
        errMsg.append(", Error code: ");
        errMsg.append(httpCode);
        errMsg.append(", Reason Phrase : ");
        errMsg.append(message);
        IOException e = new IOException(errMsg.toString());
        LogManager.logError(LogConstants.CTX_CONNECTOR, e, "Error executing http request");
        if (failOnHttpError)
            throw e;
    }
}
