package com.njzscloud.common.core.ienum;

import cn.hutool.core.collection.CollUtil;
import com.njzscloud.common.core.thread.SyncUtil;

import java.util.*;

public abstract class DictManager {
    Map<String, List<DictItem>> cache = new HashMap<>();

    public abstract List<DictItem> load(String key);

    public DictItem get(String key, String val) {
        return SyncUtil.syncR("com.njzscloud.common.core.ienum.DictManager", () -> {
            Optional<DictItem> dictItemOpt = SyncUtil.syncR(key, () -> {
                List<DictItem> dictItems = cache.get(key);
                if (CollUtil.isEmpty(dictItems)) return Optional.empty();
                return dictItems.stream().filter(it -> Objects.equals(it.getVal(), val)).findFirst();
            });

            if (dictItemOpt.isPresent()) {
                return dictItemOpt.get();
            }

            dictItemOpt = SyncUtil.syncW(key, () -> {
                List<DictItem> dictItems = cache.get(key);
                if (CollUtil.isEmpty(dictItems)) {
                    List<DictItem> itemList = load(key);
                    if (CollUtil.isNotEmpty(itemList)) {
                        cache.put(key, itemList);
                        return itemList.stream().filter(it -> Objects.equals(it.getVal(), val)).findFirst();
                    }
                    return Optional.empty();
                }
                return dictItems.stream().filter(it -> Objects.equals(it.getVal(), val)).findFirst();
            });

            return dictItemOpt.orElse(null);
        });
    }

    public void clear() {
        SyncUtil.syncW("com.njzscloud.common.core.ienum.DictManager", () -> cache.clear());
    }

    public void remove(String key) {
        SyncUtil.syncW("com.njzscloud.common.core.ienum.DictManager", () -> cache.remove(key));
    }
}
