package com.njzscloud.common.cache;

import com.njzscloud.common.core.thread.SyncUtil;

import java.util.function.Supplier;

public class DualCache implements Cache {
    private final Cache FIRST_CACHE;
    private final Cache SECOND_CACHE;

    public DualCache(Cache firstCache, Cache secondCache) {
        FIRST_CACHE = firstCache;
        SECOND_CACHE = secondCache;
    }

    @Override
    public <T> T get(String key) {
        return SyncUtil.syncR(key, () -> FIRST_CACHE.get(key, () -> SECOND_CACHE.get(key)));
    }

    @Override
    public <T> T get(String key, Supplier<T> supplier) {
        return SyncUtil.syncW(key, () -> FIRST_CACHE.get(key, () -> SECOND_CACHE.get(key, supplier)));
    }

    @Override
    public <T> T get(String key, long timeout, Supplier<T> supplier) {
        return SyncUtil.syncW(key, () -> FIRST_CACHE.get(key, timeout, () -> SECOND_CACHE.get(key, timeout, supplier)));
    }

    @Override
    public void put(String key, Object value) {
        SyncUtil.syncW(key, () -> {
            FIRST_CACHE.put(key, value);
            SECOND_CACHE.put(key, value);
        });
    }

    @Override
    public void put(String key, Object value, long timeout) {
        SyncUtil.syncW(key, () -> {
            FIRST_CACHE.put(key, value);
            SECOND_CACHE.put(key, value, timeout);
        });
    }

    @Override
    public void remove(String key) {
        SyncUtil.syncW(key, () -> {
            FIRST_CACHE.remove(key);
            SECOND_CACHE.remove(key);
        });
    }
}


