package cn.axzo.msg.center.message.service.todo.mybatis;

import cn.axzo.msg.center.inside.notices.config.PendingMessageBizConfig;
import com.alibaba.druid.sql.SQLUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.sql.Statement;

/**
 * @author yanglin
 */
@Slf4j
@Intercepts(value = {
        @Signature(type = StatementHandler.class, method = "parameterize", args = {Statement.class})
})
@RequiredArgsConstructor
class LogExecSQLInterceptor implements Interceptor {

    private final PendingMessageBizConfig cfg;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object proceed = invocation.proceed();
        if (cfg.isLogExecSQL()) {
            String sql = SQLAccessor.getSQL(invocation);
            if (StringUtils.isNotBlank(sql)) {
                sql = sql.replaceAll("[\r\n]", " ");
                if (cfg.isFormatExecSQL())
                    log.info("\n{}", SQLUtils.formatMySql(sql));
                else
                    log.info("{}", sql);
            }
        }
        return proceed;
    }

}