//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.chushang.common.feign.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.util.ObjectUtils;

public class TransferFilter implements Filter {
    private static final ThreadLocal<JSONObject> current = new ThreadLocal();
    private static final String charHax = "0123456789ABCDEF";

    public TransferFilter() {
    }

    public static <T> T get(String key, Class<T> type) {
        JSONObject json = current.get();
        return json != null && json.containsKey(key) ? json.getObject(key, type) : null;
    }

    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)arg0;
        String json = req.getHeader("transfer");
        if (!ObjectUtils.isEmpty(json)) {
            current.set(JSONObject.parseObject(new String(this.hexStringToBytes(json))));
        }

        arg2.doFilter(arg0, arg1);
        current.remove();
    }

    public byte[] hexStringToBytes(String hexString) {
        if (hexString != null && !hexString.equals("")) {
            hexString = hexString.toUpperCase();
            int length = hexString.length() / 2;
            char[] hexChars = hexString.toCharArray();
            byte[] d = new byte[length];

            for(int i = 0; i < length; ++i) {
                int pos = i * 2;
                d[i] = (byte)(this.charToByte(hexChars[pos]) << 4 | this.charToByte(hexChars[pos + 1]));
            }

            return d;
        } else {
            return null;
        }
    }

    private byte charToByte(char c) {
        return (byte)"0123456789ABCDEF".indexOf(c);
    }
}
