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

import cn.axzo.msg.center.inside.notices.config.DiagnosisProps;
import lombok.RequiredArgsConstructor;
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 org.springframework.beans.factory.ListableBeanFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

/**
 * @author yanglin
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare",
                args = {Connection.class, Integer.class})
})
@RequiredArgsConstructor
public class RowCountInterceptor implements Interceptor {

    private final DiagnosisProps props;
    private final ListableBeanFactory beanFactory;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Statement stmt = (Statement)invocation.proceed();
        if (!props.getRowCount().isEnable()) return stmt;
        if (!(stmt instanceof PreparedStatement)) return stmt;
        return new ProxyStatement((PreparedStatement)stmt, props, beanFactory);
    }

}