package com.storlead.framework.web.wrapper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.storlead.framework.core.context.Context;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

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.Charset;
import java.util.*;

/**
 * @program: storlead-storlead-mail-platform
 * @description:
 * @author: chenkq
 * @create: 2025-06-17 15:49
 */
public class JsonRequestWrapper extends HttpServletRequestWrapper {

    private byte [] body;

    public JsonRequestWrapper(HttpServletRequest request) {
        super(request);
        try {
            Map map = Context.getContext().getAttribute("httpJsonRequestParam", Map.class);
            if (map != null) {
                body = JSONObject.toJSON(map).toString().getBytes(Charset.forName("UTF-8"));
            }
            List list = Context.getContext().getAttribute("httpJsonRequestListParam", List.class);
            if (!CollectionUtils.isEmpty(list)) {
                body = JSONObject.toJSON(list).toString().getBytes(Charset.forName("UTF-8"));
            }
        }catch (Exception e) {
            System.out.println("JsonRequestWrapper"+e.getMessage());
        }
    }

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

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

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

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

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    @Override
    public String getParameter(String name) {
        String[] values = this.getParameterValues(name);
        if (values != null) {
            return values[0];
        }
        return null;
    }

    @Override
    public String[] getParameterValues(String name) {
        @SuppressWarnings("unchecked")
        Map<String, Object> jsonParamMap = Context.getContext().getAttribute("httpJsonRequestParam", Map.class);
        Object value = jsonParamMap.get(name);
        if (value == null) {
            // 不是特殊参数， 直接返回
            return super.getParameterValues(name);
        }
        if (value instanceof List) {
            List vgs = (List)value;
            String[] arr =  this.toArray(StringUtils.join(vgs,","));
            return arr;
        }
        if (value instanceof Map) {
            String jsonStr = JSON.toJSONString(value);
            String[] arr =  this.toArray(jsonStr);
            return arr;
        }
        String[] ss =  this.toArray(value);
        return ss;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> parameterMap = super.getParameterMap();

        Map<String, String[]> newParameterMap = new HashMap<>();
        if (parameterMap != null) {
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                newParameterMap.put(entry.getKey(), entry.getValue());
            }
        }

        @SuppressWarnings("unchecked")
        Map<String, Object> jsonParamMap = Context.getContext().getAttribute("httpJsonRequestParam", Map.class);
        for (Map.Entry<String, Object> m : jsonParamMap.entrySet()) {
            newParameterMap.put(m.getKey(), this.toArray(m.getValue()));
        }

        return newParameterMap;
    }

    @Override
    public Enumeration<String> getParameterNames() {
        Enumeration<String> enumeration = super.getParameterNames();

        Vector<String> vector = new Vector<String>();
        @SuppressWarnings("unchecked")
        Map<String, Object> jsonParamMap = Context.getContext().getAttribute("httpJsonRequestParam", Map.class);
        for (Map.Entry<String, Object> m : jsonParamMap.entrySet()) {
            vector.add(m.getKey());
        }

        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            vector.add(name);
        }
        return vector.elements();
    }


    @SuppressWarnings("unused")
    private String[] toArray(String context) {
        if (context == null) {
            return null;
        }
        return new String[]{context};
    }

    private String[] toArray(Object context) {
        if (context == null) {
            return null;
        }
        String vars = context.toString();
        return new String[]{vars};
    }
}
