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

import java.io.File;

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

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.eactive.eai.rms.common.context.MonitoringContext;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.FileAppender;



public class DynamicLogInterceptor extends HandlerInterceptorAdapter{
	private static final Logger logger = (Logger) LoggerFactory.getLogger("DYNAMIC_LOGGER");
	
	@Autowired
	@Qualifier("monitoringContext")
	private MonitoringContext monitoringContext;
	
	@Override 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		org.springframework.web.method.HandlerMethod h = (org.springframework.web.method.HandlerMethod)handler;
    	String fullName = h.getBeanType().getName();
		Object obj = null;
		try{
        	obj = Class.forName(fullName).newInstance();
    	}catch(Exception e){
    		logger.error("class for name " + fullName);
    		return false;
    	}
		
		if ((obj != null && obj instanceof  DynamicLogController)){
	    	HandlerMethod hm = null;
	    	Object controller = null;
	    	PatternLayoutEncoder layout = null;
	    	FileAppender appender = null;

	    	if(handler instanceof HandlerMethod){
	        	hm = (HandlerMethod) handler;
	        	controller = hm.getBean();  		
	    	}else{
	    		controller = handler;
	    	}
	    	String logKey = request.getParameter("logKey");
	    	String ctrlName = controller.getClass().getSimpleName();
	    	LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
	    	
	    	String fileName ="" ;
	    	if (logKey != null){
	    		String pattern="[%d{yyyy-MM-dd HH:mm:ss}] %5p (%F:%L) - %m%n";
		        PatternLayoutEncoder ple = new PatternLayoutEncoder();
		        ple.setPattern( pattern );
		        ple.setContext(lc);
		        ple.start();
	        	String filePath = monitoringContext.getStringProperty("log.dynamic.path", "/log/elink/ems/dynamiclog/");
	        	//fileName = "/fslog/eai/fileDown/"+ctrlName+"/"+logKey+".log";
	        	fileName = filePath+ctrlName+File.separator+logKey+".log";
	        	appender = new FileAppender();
	        	appender.setContext(lc);
	        	//appender.setName(logKey);
	        	appender.setFile(fileName);
	        	appender.setEncoder(ple);
	        	appender.start();
	        	
	        	DynamicLogContext.set(logKey, appender);
	        	appender.addFilter(new DynamicLogFilter(logKey));
	        	logger.setLevel(Level.DEBUG);
	        	logger.setAdditive(false);
	        	logger.addAppender(appender);
	        	
	        	logger.info("DynamicLog fileName : " + fileName + " , logKey : "+ logKey);
	    		
	    	}
			return true;
		 } else {
	        return true;
		 }
    }
	 
	@Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object controller, Exception ex) throws Exception {
		FileAppender appender = DynamicLogContext.getAppender();
		if(appender != null){
            StringBuilder buf = new StringBuilder();
            buf.append(controller.getClass().getName()).append(".").append(request.getRequestURI()).append(" end!!");
            logger.debug(buf.toString());
            logger.info("DynamicLog key : "+ DynamicLogContext.getKey() +" ,  appender : " + appender );
            appender.stop();
            logger.detachAppender(appender);
            appender.getEncoder().stop();
            appender.stop();
            DynamicLogContext.remove();
		}
    }

}
