package ru.yandex.autotests.httpclient.lite.core;


import org.apache.http.*;
import org.apache.http.entity.ContentType;
import org.apache.http.util.Asserts;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static ch.lambdaj.Lambda.*;
import static org.hamcrest.Matchers.equalTo;
import static ru.yandex.autotests.httpclient.lite.utils.HttpUtils.getUrlParameterValue;

/**
 * @author Roman Kuhta (kuhtich@yandex-team.ru)
 */
public class BackEndResponse {
    public BackEndResponse(StatusLine statusLine, HttpEntity httpEntity, Header[] headers) {
        this.statusLine = statusLine;
        this.httpEntity = httpEntity;
        this.headers = Arrays.asList(headers);
    }

    protected HttpEntity httpEntity;
    protected List<Header> headers;
    protected ResponseContent responseContent;
    protected StatusLine statusLine;

    public StatusLine getStatusLine() {
        return statusLine;
    }

    public List<Header> getHeaders() {
        return headers;
    }

    public HttpEntity getHttpEntity() {
        return httpEntity;
    }

    public ResponseContent getResponseContent() {
        if(responseContent == null) {
            try {
                responseContent = new ResponseContent(EntityUtils.toByteArray(httpEntity),
                        ContentType.getOrDefault(httpEntity));
            } catch (IOException e) {
                responseContent = ResponseContent.NO_CONTENT;
            }
        }
        return responseContent;
    }

    public Header getHeader(String headerName) {
        return selectFirst(headers, having(on(Header.class).getName(), equalTo(headerName)));
    }

    public HeaderElement getHeaderElement(Header header, String headerElementName) {
        return selectFirst(Arrays.asList(header.getElements()),
                having(on(HeaderElement.class).getName(), equalTo(headerElementName)));
    }

    public String getParameterFromRedirect(String parameterName) {
        Header location = this.getHeader(HttpHeaders.LOCATION);
        Asserts.notNull(location, "Redirect location");
        return getUrlParameterValue(location.getValue(), parameterName);
    }
}
