package com.eactive.httpmockserver.api.dto;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class MockRequest {

    public static Map<String, String> parseQueryString(HttpServletRequest request) {
        Map<String, String> queryParams = new HashMap<>();
        String queryString = request.getQueryString();
        if (queryString != null) {
            String[] queryParamsArr = queryString.split("&");
            for (String queryParam : queryParamsArr) {
                String[] pair = queryParam.split("=");
                String key = pair[0];
                String value = "";
                if (pair.length > 1) {
                    value = pair[1];
                }
                queryParams.put(key, value);
            }
        }
        return queryParams;
    }

    public MockRequest(HttpServletRequest request) throws IOException {
        this.method = request.getMethod();
        this.uri = request.getRequestURI();
        this.headers = Collections.list(request.getHeaderNames()).stream()
                .collect(Collectors.toMap(name -> name, request::getHeader));

        this.params = parseQueryString(request);

        this.body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
    }

    private String uri;
    private String method;
    private String body;

    private Map<String, String> headers;

    private Map<String, String> params;

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    public String getHeader(String key) {
        return this.headers.get(key);
    }

    public String getParam(String key) {
        return this.params.get(key);
    }

    public Map<String, String> getParams() {
        return params;
    }

    public void setParams(Map<String, String> params) {
        this.params = params;
    }
}
