package com.yonge.toolset.datasource.interceptor;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yonge.toolset.datasource.DataSourceContextHolder;

public class DataSourceInterceptor extends HandlerInterceptorAdapter {

	private static final String DATA_SOURCE_ID = "datasourceId";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String tenantId = request.getHeader(DATA_SOURCE_ID);
		if (StringUtils.isBlank(tenantId)) {
			tenantId = request.getParameter(DATA_SOURCE_ID);
		}
		if (StringUtils.isBlank(tenantId)) {
			tenantId = (String) request.getAttribute(DATA_SOURCE_ID);
		}
		if(StringUtils.isNotBlank(tenantId)){
			DataSourceContextHolder.setDataSourceKey(tenantId);
		}

		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		DataSourceContextHolder.clearDataSourceKey();
	}

}
