package dst.ass1.jpa.interceptor;

import org.hibernate.EmptyInterceptor;

import java.util.concurrent.atomic.AtomicLong;

public class SQLInterceptor extends EmptyInterceptor {
    private static final long serialVersionUID = -3082243834965597947L;
    private static boolean verbose = false;
    private static AtomicLong counter = new AtomicLong(0);


    public static void resetCounter() {
        SQLInterceptor.counter.set(0);
    }

    public static int getSelectCount() {
        return (int) SQLInterceptor.counter.get();
    }

    /**
     * If the verbose argument is set, the interceptor prints the intercepted SQL statements to System.out.
     *
     * @param verbose whether or not to be verbose
     */
    public static void setVerbose(boolean verbose) {
        SQLInterceptor.verbose = verbose;
    }

    @Override
    public String onPrepareStatement(String sql) {
        if (verbose) System.out.println("SQL: " + sql);

        if (sql.toLowerCase().matches("select.*from.*lecturer.*") || sql.toLowerCase().matches("select.*from.*lesson.*")) {
            long newval = SQLInterceptor.counter.incrementAndGet();
            if (verbose) System.out.println("Count increased to: " + newval);
        }
        return sql;
    }
}
