package weaver.mobile.plugin.ecology;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import weaver.hrm.User;
import weaver.mobile.plugin.ecology.service.AuthService;
import weaver.mobile.plugin.ecology.service.PluginServiceImpl;

public class MobileFilter implements Filter {
	
	public static ThreadLocal<Boolean> isMobile = new ThreadLocal<Boolean>();

	public void init(FilterConfig config) throws ServletException {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			PluginServiceImpl ps = new PluginServiceImpl();
			AuthService as = new AuthService();

			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse res = (HttpServletResponse) response;
			
			String requestUri = req.getRequestURI();
		    String querystring = req.getQueryString();
		    
		    String sessionkey = "";
		    
		    MobileFilter.isMobile.set(true);
		    
		    String[] parameters = StringUtils.split(querystring, '&');
		    if(parameters != null) {
		    	for(int i=0; i<parameters.length; i++) {
		    		String[] param = StringUtils.split(parameters[i], '=');
		    		if(param != null && param.length >= 2 && "sessionkey".equals(param[0])) {
		    			sessionkey = param[1];
		    			break;
		    		}
		    	}
		    }
		    boolean verify = ps.verify(sessionkey);
		    boolean isFileDownload = "/mobile/plugin/Download.jsp".equalsIgnoreCase(requestUri);
		    
	    	if(StringUtils.isNotEmpty(sessionkey)&&verify&&!isFileDownload) {
	    		User user = (User) req.getSession(true).getAttribute("weaver_user@bean");
	    		if(user==null) {
	    			user = as.getCurrUser(sessionkey);
	    			if(user != null) {
	    				req.getSession(true).setAttribute("weaver_user@bean",user);
	    			}
	    		}
	    	}
    		
			String timezone = req.getHeader("EMobile_Timezone");
			if(timezone != null){
				req.getSession(true).setAttribute("timeZone",timezone);
			}

	    	chain.doFilter(req, res);
	    	
	    	if(StringUtils.isNotEmpty(sessionkey)&&verify&&!isFileDownload) {
	    		HttpSession sess = req.getSession(false);
    	    	if(sess!=null){
    	    		User user = (User) sess.getAttribute("weaver_user@bean");
    	    		if(user!=null) {
    	    	    	sess.invalidate();
    	    		}
    	    	}
	    		
	    	}
		} catch(Exception e) {
			e.printStackTrace();
			throw new ServletException(e.getMessage(),e);
		}finally{
			 MobileFilter.isMobile.set(false);
		}
	}
}
