package com.keao.edu.common.tenant;

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

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

public class TenantInterceptor extends HandlerInterceptorAdapter {

	private static final String TENANT_ID = "tenantId";
	private static final String ORGAN_ID = "organId";

	@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);
		}
		TenantContextHolder.setTenantId(tenantId);
		String organId = request.getHeader(ORGAN_ID);
		if (StringUtils.isEmpty(organId)) {
			organId = request.getParameter(ORGAN_ID);
		}
		if(StringUtils.isNotEmpty(organId)){
			OrganContextHolder.setOrganId(Integer.parseInt(organId));
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		TenantContextHolder.clearTenantId();
		OrganContextHolder.clearOrganId();
	}

}
