package com.eactive.kakao.rolling.impl;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.EmptyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import com.eactive.kakao.rolling.RollingTableInterceptor;
import com.eactive.kakao.rolling.TableSuffixResolver;

public class RollingTableInterceptorImpl extends EmptyInterceptor implements RollingTableInterceptor {

	private static final long serialVersionUID = 1L;

	protected static final String[] TARGET_TABLE_NAMES = new String[] { "tseaihe01", "tseaihe02", "tseaims02",
			"tseaifr01", "tseaifr03", "tseaihs04", "tseaihs05", "tseaifr06", "tseaitr07", "tseaitr08", "tseaitr01",
			"tseaitr02", "tseaitr03", "tseaihs14", "tseaihs15" };

	@Lazy
	@Autowired
	private transient TableSuffixResolver tableSuffixResolver;

	@Override
	public String onPrepareStatement(String sql) {

		if (!StringUtils.containsAny(sql, TARGET_TABLE_NAMES)) {
			return sql;
		}

		String currentSuffix = tableSuffixResolver.getCurrentSuffix();
		for (String tableName : TARGET_TABLE_NAMES) {
			if (StringUtils.contains(sql, tableName)) {
				sql = StringUtils.replace(sql, tableName, tableName + currentSuffix);
			}
		}
		return sql;
	}

}
