package cc.smtweb.framework.core.mvc.scheduler;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Job执行队列
 *
 * @author xkliu
 */
@Slf4j
public abstract class AbstractJobQueue {
    private AtomicLong lastTime = new AtomicLong();
    private ReentrantLock lock = new ReentrantLock();
    @Getter
    private AbstractJobExecutor jobExecutor;

    public AbstractJobQueue(AbstractJobExecutor jobExecutor) {
        this.jobExecutor = jobExecutor;
    }

    public void execute(AbstractJob job) {
        try {
            // 组织断点对象参数
            Map<String, Object> params = null;
            SchedulerPoint schedulerPoint = null;
            if (job.hasPointParam) {
                schedulerPoint = jobExecutor.loadBreakPoint(job);
                if (schedulerPoint != null) {
                    params = new HashMap<>(1);
                    params.put(SchedulerPoint.class.getName(), schedulerPoint);
                }
            }

            job.method.invoke(jobExecutor.getBeanContext(), params, null, null);

            if (job.hasPointParam) {
                jobExecutor.saveBreakPoint(job, schedulerPoint);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    public long getLastTime() {
        return lastTime.get();
    }

    protected boolean tryLock() {
        boolean result = lock.tryLock();

        if (result) {
            lastTime.set(System.currentTimeMillis());
        }

        return result;
    }

    protected void unlock() {
        lastTime.set(0);
        lock.unlock();
    }

    public void updateLastTime() {
        lastTime.set(System.currentTimeMillis());
    }
}
