package com.eactive.eai.rms.common.interceptor;

import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.eactive.eai.rms.common.logging.UserAccessLogger;

public class RequestParameterLoggingInterceptor extends
        HandlerInterceptorAdapter {
	
    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
    	HandlerMethod hm = null;
    	Object controller = null;
    	
    	if(handler instanceof HandlerMethod){
        	hm = (HandlerMethod) handler;
        	controller = hm.getBean();  		
    	}else{
    		controller = handler;
    	}

    	Logger logger = Logger.getLogger(controller.getClass());

        StringBuilder buffer = new StringBuilder();
        if (logger.isDebugEnabled()) {
            buffer.append(controller.getClass().getName()).append(".").append(
                    request.getRequestURI()).append(" start!!");

            buffer.append("\n").append("request parameters : ");

            for (@SuppressWarnings("rawtypes")
			Enumeration enu = request.getParameterNames(); enu
                    .hasMoreElements();) {
                String parameterName = (String) enu.nextElement();
                buffer.append("{");
                buffer.append(parameterName + "="
                        + request.getParameter(parameterName));
                buffer.append("} ,");
            }
            logger.debug(buffer.toString());
        }
        
        // UserAccessLogger �׽�Ʈ
        // �αװ� �ʹ� ���� ���´�
        {
            String cmd = request.getParameter("cmd");
            if( cmd == null ) {
                cmd = request.getParameter("scr_name");
            }
            UserAccessLogger.log(request, controller.getClass().getSimpleName(), "*", "cmd=" + cmd);        
         }
        
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object controller, Exception ex)
            throws Exception {
    	Logger logger = Logger.getLogger(controller.getClass());
        if (logger.isDebugEnabled()) {
            StringBuilder buf = new StringBuilder();
            buf.append(controller.getClass().getName()).append(".").append(
                    request.getRequestURI()).append(" end!!");
            logger.debug(buf.toString());
        }
    }

    @Override
    @SuppressWarnings("rawtypes")
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object controller,
            ModelAndView modelAndView) throws Exception {

    	Logger logger = Logger.getLogger(controller.getClass());
        if (logger.isDebugEnabled()) {
            StringBuilder buf = new StringBuilder();
            buf.append(controller.getClass().getName()).append(".").append(
                    request.getRequestURI()).append(" processFinish!!");

            buf.append("\n").append(" >>>ModelAndView : ");
            if (modelAndView != null) {

				Map model = modelAndView.getModel();

                if (modelAndView.isReference()) {
                    buf.append("reference to view with name '").append(
                            modelAndView.getView()).append("'");
                } else {
                    buf.append("materialized View is [").append(
                            modelAndView.getView()).append(']');
                }

                buf.append("; model is ").append("\n");

                if (model != null) {
                    for (Iterator it = model.keySet().iterator(); it.hasNext();) {
                        Object key = it.next();
                        Object o = model.get(key);

                        if (o instanceof Collection) {
                            Collection collection = (Collection) o;
                            buf.append(key).append("(").append(
                                    collection.size()).append(")")
                                    .append(",\n");
                        } else if (o instanceof Map) {
                            Map map = (Map) o;
                            buf.append(key).append("(").append(map.size())
                                    .append(")").append(",\n");
                        } else {
                            buf.append(key).append(",\n");
                        }

                    }
                }
            }
            logger.debug(buf.toString());
        }
    }

}
