/*
 * Copyright 2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.internal.resource.transport.http;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.utils.HttpClientUtils;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

/**
 * An HTTP response from an {@link ApacheCommonsHttpClient}.
 */
@NullMarked
public class ApacheHttpResponse implements HttpClient.Response {

    private final String method;
    private final URI effectiveUri;
    private final CloseableHttpResponse httpResponse;
    private boolean closed;

    ApacheHttpResponse(String method, URI effectiveUri, CloseableHttpResponse httpResponse) {
        this.method = method;
        this.effectiveUri = effectiveUri;
        this.httpResponse = httpResponse;
    }

    @Override
    public @Nullable String getHeader(String name) {
        Header header = httpResponse.getFirstHeader(name);
        return header == null ? null : header.getValue();
    }

    @Override
    public InputStream getContent() throws IOException {
        HttpEntity entity = httpResponse.getEntity();
        if (entity == null) {
            throw new IOException(String.format("Response %d: %s has no content!", getStatusCode(), getStatusReason()));
        }
        return entity.getContent();
    }

    @Override
    public int getStatusCode() {
        return httpResponse.getStatusLine().getStatusCode();
    }

    @Override
    public String getStatusReason() {
        return httpResponse.getStatusLine().getReasonPhrase();
    }

    @Override
    public void close() {
        if (!closed) {
            closed = true;
            HttpClientUtils.closeQuietly(httpResponse);
        }
    }

    @Override
    public String getMethod() {
        return method;
    }

    @Override
    public URI getEffectiveUri() {
        return effectiveUri;
    }

}
