package vip.xiaonuo.coldchain.core.cache.monitordevice.impl;

/**
 * @author jackzhou
 * @version 1.0
 * @project jfcloud-coldchain
 * @description
 * @date 2024/11/19 17:35:44
 */

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import vip.xiaonuo.coldchain.core.cache.monitordevice.MonitorDeviceCacheService;
import vip.xiaonuo.common.cache.CommonCacheOperator;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Redis 缓存实现类
 */
@Component
@RequiredArgsConstructor
public class RedisMonitorDeviceCacheService implements MonitorDeviceCacheService {
    private static final String CACHE_KEY_PREFIX = "Cache:MonitorDevice:";
    private final CommonCacheOperator commonCacheOperator;

    @Override
    public void cacheDevice(String deviceCode, String deviceModel) {
        commonCacheOperator.put(CACHE_KEY_PREFIX + deviceCode, deviceModel);
    }

    @Override
    public String getDeviceModel(String deviceCode) {
        if (exists(deviceCode)) {
            return (String) commonCacheOperator.get(CACHE_KEY_PREFIX + deviceCode);
        } else {
            return null;
        }
    }

    @Override
    public boolean exists(String deviceCode) {
        return commonCacheOperator.get(CACHE_KEY_PREFIX + deviceCode) != null;
    }

    @Override
    public void removeDevice(String deviceCode) {
        commonCacheOperator.remove(CACHE_KEY_PREFIX + deviceCode);
    }

    @Override
    public void removeBatch(String pattern) {
        commonCacheOperator.removeBatch(CACHE_KEY_PREFIX + pattern);
    }

    @Override
    public Set<String> getAllDeviceCodes() {
        return commonCacheOperator.getAllKeys().stream()
                .filter(key -> key.startsWith(CACHE_KEY_PREFIX))
                .map(key -> key.replace(CACHE_KEY_PREFIX, ""))
                .collect(Collectors.toSet());
    }

    @Override
    public List<String> getAllDeviceModels() {
        return commonCacheOperator.getAllKeys().stream()
                .filter(key -> key.startsWith(CACHE_KEY_PREFIX))
                .map(key -> (String) commonCacheOperator.get(key))
                .collect(Collectors.toList());
    }
}
