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

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import ru.yandex.autotests.httpclient.lite.core.IFormParameters;
import ru.yandex.autotests.httpclient.lite.core.exceptions.BackEndClientException;
import ru.yandex.autotests.httpclient.lite.core.exceptions.BackEndClientParametersException;
import ru.yandex.autotests.httpclient.lite.core.exceptions.ParameterNotFoundException;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import static ch.lambdaj.Lambda.*;
import static org.hamcrest.Matchers.equalTo;


/**
 * @author Roman Kuhta (kuhtich@yandex-team.ru)
 */
public class HttpUtils {

    public static List<NameValuePair> aggregate(IFormParameters... params) {
        List<NameValuePair> requestParams = new ArrayList<>();
        for (IFormParameters param : params) {
            requestParams.addAll(param.getParameters());
        }
        return requestParams;
    }

    @SafeVarargs
    public static List<NameValuePair> aggregate(List<NameValuePair>... params) {
        List<NameValuePair> requestParams = new ArrayList<>();
        for (List<NameValuePair> param : params) {
            requestParams.addAll(param);
        }
        return requestParams;
    }

    public static List<NameValuePair> getMethodParams(HttpUriRequest method) {
        List<NameValuePair> params = new ArrayList<>();
        if(method instanceof HttpPost || method instanceof HttpPut) {
            try {
                params = aggregate(params, URLEncodedUtils.parse(
                        ((HttpEntityEnclosingRequestBase) method).getEntity()));
            } catch (IOException e) {
                throw new BackEndClientException("Unexpected error while logging", e);
            }
        }
        return aggregate(params, parseUrlParameters(method.getURI().toString()));
    }

    public static String getURI(HttpUriRequest method) {
        URI uri = method.getURI();
        return buildURI(new URIBuilder()
                .setScheme(uri.getScheme())
                .setHost(uri.getHost())
                .setPath(uri.getPath())).toString();
    }

    public static String getUrlParameterValue(List<NameValuePair> params, String parameterName) {
        NameValuePair pair = selectFirst(params,
                having(on(NameValuePair.class).getName(), equalTo(parameterName)));
        if(pair == null) {
            throw new ParameterNotFoundException("Parameter not found " + parameterName);
        }
        return pair.getValue();
    }

    public static String getUrlParameterValue(String url, String parameterName) {
        return getUrlParameterValue(parseUrlParameters(url), parameterName);
    }

    public static URI buildURI(URIBuilder builder) {
        try {
            return builder.build();
        } catch (URISyntaxException e) {
            throw new BackEndClientParametersException("Failed to parse request uri", e);
        }
    }

    public static List<NameValuePair> parseUrlParameters(String url) {
        return URLEncodedUtils.parse(url, Consts.UTF_8, '?', '&', '#');
    }

    public static HttpEntity buildEntity(List<NameValuePair> params) {
        return new UrlEncodedFormEntity(params, Consts.UTF_8);
    }

    public static List<NameValuePair> emptyParams() {
        return new ArrayList<>();
    }
}
