package com.easyagents.scheduler.quartz;

import org.quartz.InterruptableJob;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;

/**
 * 将 Quartz Job 委派给当前节点 {@link QuartzRuntime} 的内部基类。
 */
abstract class AbstractDispatchJob implements InterruptableJob {

    private volatile Thread executionThread;

    /**
     * 从 SchedulerContext 定位运行时并分发任务。
     *
     * @param context Quartz 执行上下文
     * @throws JobExecutionException 运行时缺失或 Handler 执行失败时抛出
     */
    @Override
    public final void execute(JobExecutionContext context) throws JobExecutionException {
        executionThread = Thread.currentThread();
        try {
            Object runtime = context.getScheduler().getContext().get(
                QuartzRuntime.SCHEDULER_CONTEXT_KEY
            );
            if (!(runtime instanceof QuartzRuntime quartzRuntime)) {
                throw new JobExecutionException("easy-agents scheduler runtime is not available");
            }
            quartzRuntime.execute(context);
        } catch (JobExecutionException exception) {
            // JobExecutionException 继承 SchedulerException，必须保留 refire 等控制语义。
            throw exception;
        } catch (SchedulerException exception) {
            throw new JobExecutionException("failed to access scheduler runtime", exception, false);
        } finally {
            executionThread = null;
        }
    }

    /**
     * 向当前 Handler 执行线程发送协作式中断信号。
     */
    @Override
    public final void interrupt() {
        Thread currentExecutionThread = executionThread;
        if (currentExecutionThread != null) {
            currentExecutionThread.interrupt();
        }
    }
}
