package org.wcs.business.redis;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.wcs.constant.ConstantData;
import org.wcs.plugin.plc.common.PlcCommonData;
import org.wcs.plugin.plc.model.SiemensDBAddress;
import org.wcs.utils.AppStringUtils;

import java.util.Set;

/**
 * PLC地址缓存
 */
@Component
@RequiredArgsConstructor
public class DbAddressRedis {


    /**
     * Redis操作类
     */
    private final StringRedisTemplate stringRedisTemplate;

    // 地址缓存key
    private final String PLC_DB_ADDRESS_REDIS_KEY = ConstantData.SYSTEM_NAME + ":PLC:DBAddress";

    /**
     * 清除PLC地址缓存
     */
    public void clearDbAddress() {
        stringRedisTemplate.delete(PLC_DB_ADDRESS_REDIS_KEY);
        Set<String> keys = stringRedisTemplate.keys(PLC_DB_ADDRESS_REDIS_KEY + ":*");
        stringRedisTemplate.delete(keys);
    }


    /**
     * 缓存PLC地址信息
     * @param dbName 地址名称
     * @param dbAddress 地址信息
     */
    public void setDbAddress(String dbName, SiemensDBAddress dbAddress) {
        stringRedisTemplate.opsForValue().set(PLC_DB_ADDRESS_REDIS_KEY + ":" + dbName, AppStringUtils.objectToString(dbAddress));
    }


    /**
     * 获取PLC地址信息
     * @param dbName 地址名称
     * @return 地址 信息
     */
    public SiemensDBAddress getDbAddress(String dbName) {
        String dbJson = stringRedisTemplate.opsForValue().get(PLC_DB_ADDRESS_REDIS_KEY + ":" + dbName);
        if(AppStringUtils.isEmpty(dbJson)) {
            return null;
        }
        return AppStringUtils.stringToObject(dbJson, SiemensDBAddress.class);
    }


}
