package net.brutex.xservices.util;

import java.sql.*;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicBoolean;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.h2.jdbcx.JdbcConnectionPool;
import org.quartz.*;

@Slf4j
@DisallowConcurrentExecution
public class LockCleanerJob implements Job, InterruptableJob {

    private final AtomicBoolean isInterrupted = new AtomicBoolean(false);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.debug("LockCleaner is executing now.");
        final Instant d = Instant.now();
        final long ts = d.toEpochMilli();
        @NonNull
        final JdbcConnectionPool mpool = (JdbcConnectionPool) context.getMergedJobDataMap().get("mdbConnection");
        final String deleteMemTable = "DELETE FROM brutex.tbl_lock where btx_validity < " + (ts-5000);

        try (Connection mcon = mpool.getConnection()){
            Statement stmt = mcon.createStatement();
            stmt.execute(deleteMemTable);
            int count = stmt.getUpdateCount();
            log.debug("LockCleaner deleted '{}' stale locks.", count);

        } catch (SQLException e) {
            log.error("Exception in SQL execution: {}", e.getMessage());
            throw new JobExecutionException(e);
        }
    }


        /**
     * <p>
     * Called by the <code>{@link Scheduler}</code> when a user
     * interrupts the <code>Job</code>.
     * </p>
     *
     * @throws UnableToInterruptJobException if there is an exception while interrupting the job.
     */
    @Override
    public synchronized void interrupt() throws UnableToInterruptJobException {
        isInterrupted.set(true);
        log.warn("LockCleanerJob received an interrupt.");
        Thread.currentThread().interrupt();
    }
}
