package org.springblade.common.auth.support;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.jasig.cas.client.util.URIBuilder;
import org.springframework.util.CollectionUtils;

public class AuthUtil {

    public static final String ACCESS_TOKEN_KEY = "accessToken";

    public static final String CONTENT_TYPE_JSON = "application/json;charset=UTF-8";

    public static final String SPLIT_CHAR_SLASH = "/";
    public static final String CHAR_OPEN_BRACE = "{";
    public static final String CHAR_CLOSE_BRACE = "}";

    public static String generateAccessToken() {
        return UUID.randomUUID().toString().trim().replaceAll("-", "");
    }

    public static String handleRequestUrl(String requestUrl, Map pathVariables) {
        if (CollectionUtils.isEmpty(pathVariables)) {
            return requestUrl;
        } else {
            String[] urlArray = requestUrl.split(SPLIT_CHAR_SLASH);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < urlArray.length; i++) {
                Set<Map.Entry> entrySet = pathVariables.entrySet();
                boolean flag = false;
                for (Map.Entry entry : entrySet) {
                    if (entry.getValue().toString().equals(urlArray[i])) {
                        flag = true;
                        stringBuilder.append(CHAR_OPEN_BRACE);
                        stringBuilder.append(entry.getKey().toString());
                        stringBuilder.append(CHAR_CLOSE_BRACE);
                    }
                }
                if (!flag) {
                    stringBuilder.append(urlArray[i]);
                }
                if (i < urlArray.length - 1) {
                    stringBuilder.append(SPLIT_CHAR_SLASH);
                }
            }
            return stringBuilder.toString();
        }
    }

    public static String constructServiceUrl(HttpServletRequest request, HttpServletResponse response, String service,
            String serverNames, String serviceParameterName, String artifactParameterName, boolean encode) {
        if (StringUtils.isNotBlank(service)) {
            return encode ? response.encodeURL(service) : service;
        } else {
            String serverName = findMatchingServerName(request, serverNames);
            URIBuilder originalRequestUrl = new URIBuilder(request.getRequestURL().toString(), encode);
            originalRequestUrl.setParameters(request.getQueryString());
            URIBuilder builder;
            if (!serverName.startsWith("https://") && !serverName.startsWith("http://")) {
                String scheme = request.isSecure() ? "https://" : "http://";
                builder = new URIBuilder(scheme + serverName, encode);
            } else {
                builder = new URIBuilder(serverName, encode);
            }

            builder.setEncodedPath(builder.getEncodedPath() + request.getRequestURI());
            List<String> serviceParameterNames = Arrays.asList(serviceParameterName.split(","));
            if (!serviceParameterNames.isEmpty() && !originalRequestUrl.getQueryParams().isEmpty()) {
                Iterator var11 = originalRequestUrl.getQueryParams().iterator();

                label72:
                while (true) {
                    while (true) {
                        URIBuilder.BasicNameValuePair pair;
                        String name;
                        do {
                            do {
                                if (!var11.hasNext()) {
                                    break label72;
                                }

                                pair = (URIBuilder.BasicNameValuePair) var11.next();
                                name = pair.getName();
                            } while (name.equals(artifactParameterName));
                        } while (serviceParameterNames.contains(name));

                        if (!name.contains("&") && !name.contains("=")) {
                            builder.addParameter(name, pair.getValue());
                        } else {
                            URIBuilder encodedParamBuilder = new URIBuilder();
                            encodedParamBuilder.setParameters(name);
                            Iterator var15 = encodedParamBuilder.getQueryParams().iterator();

                            while (var15.hasNext()) {
                                URIBuilder.BasicNameValuePair pair2 = (URIBuilder.BasicNameValuePair) var15.next();
                                String name2 = pair2.getName();
                                if (!name2.equals(artifactParameterName) && !serviceParameterNames.contains(name2)) {
                                    builder.addParameter(name2, pair2.getValue());
                                }
                            }
                        }
                    }
                }
            }

            String result = builder.toString();
            String returnValue = encode ? response.encodeURL(result) : result;
            return returnValue;
        }
    }

    protected static String findMatchingServerName(HttpServletRequest request, String serverName) {
        String[] serverNames = serverName.split(" ");
        if (serverNames.length != 0 && serverNames.length != 1) {
            String host = request.getHeader("Host");
            String xHost = request.getHeader("X-Forwarded-Host");
            String comparisonHost;
            if (xHost != null && host == "localhost") {
                comparisonHost = xHost;
            } else {
                comparisonHost = host;
            }

            if (comparisonHost == null) {
                return serverName;
            } else {
                String[] var6 = serverNames;
                int var7 = serverNames.length;

                for (int var8 = 0; var8 < var7; ++var8) {
                    String server = var6[var8];
                    String lowerCaseServer = server.toLowerCase();
                    if (lowerCaseServer.contains(comparisonHost)) {
                        return server;
                    }
                }

                return serverNames[0];
            }
        } else {
            return serverName;
        }
    }

}