package com.house365.web.filter;

import java.io.IOException;

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

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.house365.beans.entity.UserEntity;
import com.house365.web.util.Constant;
import com.house365.ws.interfaces.server.IUser;

/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 *
 * @author hqc
 */
public class AuthBindFilter implements Filter {

    /**
     * 自动注入账户WS实现
     */
    private IUser user;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext context = filterConfig.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
        user = (IUser) ctx.getBean("user");
    }

    @Override
    public void doFilter(
        ServletRequest request, ServletResponse response, FilterChain chain
    ) throws IOException, ServletException {

        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpSession session = servletRequest.getSession(false);

        String id = servletRequest.getParameter("userId");
        if (id != null) {
            UserEntity entity = user.getUserById(Integer.valueOf(id)).getEntity();
            session = servletRequest.getSession(true);
            session.setAttribute(Constant.SESSION_LOCAL_USER, entity);
            chain.doFilter(request, response);
        }

        Object obj = null;
        if (session != null) {
            obj = session.getAttribute(Constant.SESSION_LOCAL_USER);
        }
        if (obj != null || servletRequest.getRequestURI().contains("/rest/interface")) {
            chain.doFilter(request, response);
        } else {
            UserEntity entity = user.getUserById(1).getEntity();
            session = servletRequest.getSession(true);
            session.setAttribute(Constant.SESSION_LOCAL_USER, entity);
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {
    }
}
