package com.blueland.bpm.manage.web;

import java.io.IOException;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.blueland.bpm.identity.model.User;
import com.blueland.bpm.manage.util.BaseUser;


public class LoginInterceptor implements HandlerInterceptor{
	private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2)  {
		log.debug("preHandle");
		String url=request.getRequestURL().toString(); 
		log.debug("url"+url);
		if(!"".equals(url) && !url.contains("login")){
			try {
				User user = BaseUser.getInstance().getSessionUser(request);
				if(null  == user){
					request.getRequestDispatcher("/pages/login.jsp").forward(request, response);  
		            return false;
				}
			} catch (Exception e) {
				e.printStackTrace();
				try {
					request.getRequestDispatcher("/pages/login.jsp").forward(request, response);
					return false;
				} catch (ServletException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return true;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		
		log.debug("afterCompletion");
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2, ModelAndView arg3) throws Exception {
		log.debug("postHandle");
	}

}
