package com.njzscloud.common.sichen.support;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public interface TaskStore {
    Map<String, FnHandle> TASK_FN = new HashMap<>();
    ReentrantReadWriteLock RW_LOCK = new ReentrantReadWriteLock();
    ReentrantReadWriteLock.ReadLock RLOCK = RW_LOCK.readLock();
    ReentrantReadWriteLock.WriteLock WLOCK = RW_LOCK.writeLock();

    static void registerFn(String name, Object obj, Method method) {
        TASK_FN.computeIfAbsent(name, k -> new FnHandle(k, obj, method));
    }

    static List<Map<Object, Object>> searchFn(String keywords) {
        var entries = TASK_FN.entrySet();
        return entries.stream().filter(it -> StrUtil.isBlank(keywords)
                || it.getKey().contains(keywords)
                || it.getValue().getDefineName().contains(keywords))
            .map(it -> MapUtil.builder()
                .put("fn", it.getKey())
                .put("defineName", it.getValue().getDefineName())
                .build())
            .toList();
    }

    static FnHandle getFn(String fn) {
        return TASK_FN.get(fn);
    }

    void registerTask(TaskInfo taskInfo);

    List<TaskInfo> loadTask(long soon);

    void updateCriticalTiming(long id, long criticalTiming);

    boolean trigger(Long id);
}
