package com.imdroid.sideslope.sal;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Layton
 * @date 2023/2/3 20:46
 */
@Component(value = "local")
public class LocalDeviceServiceImpl implements DeviceService {
    /*static RemovalListener<String, Device> removalListener = new RemovalListener<String, Device>() {
        public void onRemoval(RemovalNotification<String, Device> removal) {

        }
    };*/
    private static final Cache<String, Device> deviceCache = CacheBuilder.newBuilder().
            expireAfterWrite(90, TimeUnit.MINUTES).build();

    private static final Cache<String, List<Device>> subDeviceCache = CacheBuilder.newBuilder().
            expireAfterWrite(10, TimeUnit.MINUTES).build();

    @Resource(name = "db")
    private DeviceService delegate;

    @Override
    public Device findByDeviceId(String deviceId) {
        Device device = deviceCache.getIfPresent(deviceId);
        if (device == null) {
            device = delegate.findByDeviceId(deviceId);
            if (device != null) {
                deviceCache.put(deviceId, device);
            }
        }
        return device;
    }

    @Override
    public List<Device> findByParentId(String parentId) {
        List<Device> device = subDeviceCache.getIfPresent(parentId);
        if (device == null) {
            device = delegate.findByParentId(parentId);
            if (device != null) {
                subDeviceCache.put(parentId, device);
            }
        }
        return device;
    }

    public void refresh(String deviceId){
        Device device = deviceCache.getIfPresent(deviceId);
        if (device != null) {
            if(device.getParentId()!=null) {
                subDeviceCache.invalidate(device.getParentId());
            }
            deviceCache.invalidate(deviceId);
        }
    }
}
