package io.geekidea.springbootplus.framework.shiro.signature;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;

/**
 * 签名检验员
 * @Author luozh
 * @Date 2022年04月14日 17:31
 * @Version 1.0
 */
public class SignatureChecker {

    /**
     * 时间戳请求最小限制(600s)
     * 设置的越小，安全系数越高，但是要注意一定的容错性
     */
    private static final long MAX_REQUEST = 10 * 60 * 1000L;

    /**
     * 签名校验
     * @Author luozh
     * @Date 2022年04月14日 05:32:32
     * @param request 请求信息
     * @param signature 签名
     * @Return appKey
     */
    public static String check(HttpServletRequest request, String signature) {


        return "";
    }

    /**
     * 获取请求入参
     *
     * @param request
     * @return
     */
    public static Map<String, Object> getParameterMap(HttpServletRequest request) {
        Map<String, Object> paramMap = new LinkedHashMap<>();
        if (request instanceof RequestWrapper) {
            RequestWrapper requestWrapper = (RequestWrapper) request;
            Map<String, Object> body = getParameterMap(requestWrapper.getRequestBody());
            if (!CollectionUtils.isEmpty(body)) {
                paramMap.putAll(body);
            }
        }
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String key = names.nextElement();
            paramMap.put(key, request.getParameter(key));
        }

        return paramMap;
    }

    /**
     * 获取参数对象
     *
     * @param params
     * @return
     */
    public static Map<String, Object> getParameterMap(byte[] params) {
        try {
            return JSON.parseObject(new String(params), Map.class);
        } catch (Exception e) {
            return convertParameterToMap(new String(params, StandardCharsets.UTF_8));
        }
    }


    /**
     * 将参数转换为Map类型
     *
     * @param param
     * @return
     */
    public static Map<String, Object> convertParameterToMap(String param) {
        if (StringUtils.isEmpty(param)) {
            return Collections.emptyMap();
        }
        Map<String, Object> pMap = Maps.newLinkedHashMap();
        String[] pArray = StringUtils.split(param, "&");
        for (int i = 0; i < pArray.length; i++) {
            String[] array = StringUtils.split(pArray[i], "=");
            if (array.length == 2) {
                pMap.put(array[0], array[1]);
            }
        }
        return pMap;
    }

}
