package com.keao.edu.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.keao.edu.datasource.DataSourceContextHolder;

public class DataSourceInterceptor extends HandlerInterceptorAdapter {

	private static final String TENANT_ID = "tenantId";

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

		return true;
	}

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

}
