package com.njzscloud.common.sichen.service;

import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.sichen.support.TaskInfo;
import com.njzscloud.common.sichen.support.TaskStore;
import lombok.RequiredArgsConstructor;

import java.util.List;

@RequiredArgsConstructor
public class CombineStoreService implements TaskStore {
    public final MemoryTaskStoreService memoryTaskStoreService;
    public final DbTaskService dbTaskService;

    @Override
    public List<TaskInfo> loadTask(long soon) {
        RLOCK.lock();
        try {
            List<TaskInfo> memTaskInfos = memoryTaskStoreService.loadTask(soon);
            if (dbTaskService != null) {
                List<TaskInfo> dbTaskInfos = dbTaskService.loadTask(soon);
                memTaskInfos.addAll(dbTaskInfos);
            }
            return memTaskInfos;
        } finally {
            RLOCK.unlock();
        }
    }

    @Override
    public boolean trigger(Long id) {
        RLOCK.lock();
        try {
            boolean trigger = memoryTaskStoreService.trigger(id);
            if (!trigger && dbTaskService != null) {
                return dbTaskService.trigger(id);
            }
            return trigger;
        } finally {
            RLOCK.unlock();
        }
    }

    @Override
    public void registerTask(TaskInfo taskInfo) {
        WLOCK.lock();
        try {
            if (dbTaskService != null) dbTaskService.registerTask(taskInfo);
            else memoryTaskStoreService.registerTask(taskInfo);
        } finally {
            WLOCK.unlock();
        }
    }

    public void updateCriticalTiming(boolean builtin, long id, long criticalTiming) {
        WLOCK.lock();
        try {
            if (builtin) memoryTaskStoreService.updateCriticalTiming(id, criticalTiming);
            else if (dbTaskService != null) {
                dbTaskService.updateCriticalTiming(id, criticalTiming);
            }
        } finally {
            WLOCK.unlock();
        }
    }

    @Override
    public void updateCriticalTiming(long id, long criticalTiming) {
        throw Exceptions.exception("勿用");
    }

}
