package study.u42;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

public final class TracePlugins {
    public static final java.util.concurrent.atomic.AtomicInteger categoryQueries = new java.util.concurrent.atomic.AtomicInteger();
    public static final List<String> events = new ArrayList<>();
    private static Object trace(String name, Invocation call) throws Throwable {
        events.add(name + ":before");
        try { return call.proceed(); } finally { events.add(name + ":after"); }
    }
    @Intercepts(@Signature(type=org.apache.ibatis.executor.statement.StatementHandler.class, method="prepare", args={java.sql.Connection.class,Integer.class}))
    public static class QueryCount implements Interceptor {
        public Object intercept(Invocation call) throws Throwable {
            if (((org.apache.ibatis.executor.statement.StatementHandler)call.getTarget()).getBoundSql().getSql().contains("SELECT id,label FROM category")) categoryQueries.incrementAndGet();
            return call.proceed();
        }
    }
    @Intercepts(@Signature(type=Executor.class, method="update", args={MappedStatement.class,Object.class}))
    public static class First implements Interceptor {
        public Object intercept(Invocation call) throws Throwable { return trace("first", call); }
    }
    @Intercepts(@Signature(type=Executor.class, method="update", args={MappedStatement.class,Object.class}))
    public static class Second implements Interceptor {
        public Object intercept(Invocation call) throws Throwable { return trace("second", call); }
    }
}
