package com.sy.coinage.core.util;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.springframework.util.ReflectionUtils;

public class CommUtils {

    public static boolean isArray(Object obj) {
        if (obj == null) {
            return false;
        }
        return obj.getClass().isArray();
    }

    @SuppressWarnings("unchecked")
    public static void printEnumeration(Object request, Object logger, String logMethod) {
        Method getAttributeNames = ReflectionUtils.findMethod(request.getClass(), "getAttributeNames");
        Method getAttribute = ReflectionUtils.findMethod(request.getClass(), "getAttribute", String.class);
        Method log = ReflectionUtils.findMethod(logger.getClass(), logMethod, String.class, Object.class, Object.class);

        Enumeration<String> attributeNames =
                        (Enumeration<String>) ReflectionUtils.invokeMethod(getAttributeNames, request);

        while (attributeNames.hasMoreElements()) {
            String name = attributeNames.nextElement();
            Object obj = ReflectionUtils.invokeMethod(getAttribute, request, name);
            String value = "";
            if (isArray(obj)) {
                value = Arrays.toString((String[]) obj);
            } else {
                value = String.valueOf(obj);
            }
            ReflectionUtils.invokeMethod(log, logger, "name: {} ,value: {}", name, value);
            // log.debug("name: {} ,value: {}", name, value);
        }

    }

    public static void WebErrorLog(Logger log, Throwable ex, HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String queryString = request.getQueryString();
        if (queryString != null && !"".equals(queryString)) {
            url.append("?").append(queryString);
        }
        // log.error("---ControllerException Handler---Host {} invokes url {} ERROR: {}",
        // request.getRemoteHost(),
        // url.toString(), ex.getMessage(), ex);
        log.error("---ControllerException Handler---invokes url {} ERROR: {}", url.toString(), ex.getMessage(), ex);
    }

}
