package com.liquidnet.commons.lang.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class CurrentUtil {
    public static final String uID = "sub";
    public static final String uTag = "u-tag";
    public static final String uToken = "u-token";
    public static final String CLI_SOURCE = "source";
    public static final String CLI_VERSION = "version";
    public static final String CLI_UNKNOWN = "unknown";

    public static String getToken() {
        String authToken = ServletUtils.getRequest().getHeader(uToken);
        return StringUtils.isEmpty(authToken) ? "" : authToken;
    }

    public static Map getTokenClaims() {
        String utag = ServletUtils.getRequest().getHeader(uTag);
        return JsonUtils.fromJson(utag, Map.class);
    }

    public static String getCurrentUid() {
        String uid = ServletUtils.getRequest().getHeader(uID);
        // TODO: 2021/5/14 dev联调API未启用token默认使用1
        return StringUtils.isEmpty(uid) ? "1" : uid;
    }

    public static String getCliSource() {
        return ServletUtils.getRequest().getHeader(CLI_SOURCE);
    }

    public static String getCliVersion() {
        return ServletUtils.getRequest().getHeader(CLI_VERSION);
    }

    public static String getCliIpAddr() {
        HttpServletRequest request = ServletUtils.getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || CLI_UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || CLI_UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || CLI_UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || CLI_UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || CLI_UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
}
