package com.yihu.hos.interceptor;

import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.tenant.model.TenantSession;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 *  web 请求拦截
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/12/26.
 */
public class WebMvcInterceptor extends HandlerInterceptorAdapter {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession();
        String servletPath = request.getServletPath();
        TenantSession tenantSession = (TenantSession) session.getAttribute(ContextAttributes.TENANT_SESSION);
        if (tenantSession!=null) {
            if (servletPath.contains("/tenant/")){
                LocalContext.getContext().setAttachment(ContextAttributes.SCHEMA, ContextAttributes.GLOBAL_DB);
            }else {
                if (ContextAttributes.GLOBAL_DB.equals(LocalContext.getContext().getAttachment(ContextAttributes.SCHEMA))){
                    //切换到租户对应数据库
                    String userSchema =  LocalContext.getContext().getAttachment(ContextAttributes.SCHEMA_TEMP);
                    LocalContext.getContext().setAttachment(ContextAttributes.SCHEMA, userSchema);
                }else {
                    LocalContext.getContext().setAttachment(ContextAttributes.SCHEMA, tenantSession.getSchema());
                    LocalContext.getContext().setAttachment(ContextAttributes.TENANT_NAME, tenantSession.getTenant());
                    LocalContext.getContext().setAttachment(ContextAttributes.SCHEMA_TEMP, tenantSession.getSchemaTemp());
                }
            }

        }
        return true;
    }

}
