package cn.pluss.platform.interceptor.wrapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {

    private Map<String, String[]> params = new HashMap<>();

    /**
     * 用于将流保存下来
     */
    private byte[] requestBody = null;

    private final Map<String, String> headers = new HashMap<>();

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> result = new HashMap<>();
        result.putAll(super.getParameterMap());
        result.putAll(params);
        return result;
    }

    @Override
    public Enumeration<String> getParameterNames() {
        Map<String, String[]> result = new HashMap<>();
        result.putAll(super.getParameterMap());
        result.putAll(params);

        Vector<String> l = new Vector<>(result.keySet());
        return l.elements();
    }

    @Override
    public String[] getParameterValues(String name) {
        Object v = params.get(name);

        if (v == null) {
            return super.getParameterValues(name);
        } else {
            return (String[]) v;
        }
    }

    @Override
    public String getParameter(String name) {
        Object v = params.get(name);
        if (v == null) {
            return super.getParameter(name);
        } else {
            String[] strArr = (String[]) v;
            if (strArr.length > 0) {
                return strArr[0];
            } else {
                return null;
            }
        }
    }

    public void addParam(String key, String... value) {
        params.put(key, value);
    }

    public void addHeader(String name,String value){
        headers.put(name, value);
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        List<String> names= Collections.list(super.getHeaderNames());
        names.addAll(headers.keySet());

        return Collections.enumeration(names);
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        List<String> list= Collections.list(super.getHeaders(name));

        if (headers.containsKey(name)){
            list.add(headers.get(name));
        }

        return Collections.enumeration(list);
    }

    @Override
    public String getHeader(String name) {
        String value=super.getHeader(name);

        if (headers.containsKey(name)){
            value=headers.get(name);
        }

        return value;
    }

    public void setRequestBody(String requestBody) {
        this.requestBody = requestBody.getBytes(StandardCharsets.UTF_8);
    }

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        try {
            String contentType = request.getContentType();
            // 这里排除表单请求
            if (contentType != null && !contentType.contains("x-www-form-urlencoded")) {
                requestBody = StreamUtils.copyToByteArray(request.getInputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ServletInputStream getInputStream() {
        if (requestBody == null) {
            requestBody = new byte[0];
        }
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody);
        return new ServletInputStream() {

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public void setReadListener(ReadListener listener) {
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public boolean isFinished() {
                return false;
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
}