package net.brutex.xservices.util;

import java.sql.*;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicBoolean;
import lombok.extern.slf4j.Slf4j;
import org.h2.jdbcx.JdbcConnectionPool;
import org.quartz.*;

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

    private final AtomicBoolean isInterrupted = new AtomicBoolean(false);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.debug("Retention job is executing now for alf event logs.");
        final Instant d = Instant.now();
        final long ts = d.toEpochMilli();
        final JdbcConnectionPool fpool = (JdbcConnectionPool) context.getMergedJobDataMap().get("fdbConnection");
        final EventmanagerConfiguration conf = (EventmanagerConfiguration)  context.getMergedJobDataMap().get(EventmanagerConfiguration.KEY);
        final String deleteMemTable = "DELETE FROM brutex.tbl_events_all where btx_timestamp < " + (ts-(conf.getLogMaxAge()*60*60*1000));

        try (Connection mcon = fpool.getConnection()) {
            Statement stmt = mcon.createStatement();
            stmt.execute(deleteMemTable);
            int count = stmt.getUpdateCount();
            log.debug("Retention job 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("Retention job received an interrupt.");
        Thread.currentThread().interrupt();
    }
}
