package com.junmp.jyzb.cache;

import com.junmp.jyzb.api.constant.JYZBConstant;
import com.junmp.jyzb.entity.Temp.HumidityAndtemperature;
import com.junmp.v2.cache.AbstractRedisCache;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Component
public class TemperatureRedisCache extends AbstractRedisCache<Object> {
    public TemperatureRedisCache(RedisTemplate<String, Object> redisTemplate) {
        super(redisTemplate);
    }

    @Override
    public String getCommonKeyPrefix() {
        return JYZBConstant.JYZB_TEMP_PREFIX;
    }

    public void addTemperatureHumidity(String warehouseId,String warehouseName,long timestamp, double humidity, double temperature,String deviceName) {
        HumidityAndtemperature data = new HumidityAndtemperature();
        data.setHumidity(humidity);
        data.setTemperature(temperature);
        data.setCreateTime(timestamp);
        data.setDeviceName(deviceName);
        data.setWarehouseId(warehouseId);
        data.setWarehouseName(warehouseName);
//        String key = warehouseId;
//        Long size = getRedisTemplate().opsForZSet().size(key);
        getRedisTemplate().opsForZSet().add("WarehouseDev:"+warehouseId, data, timestamp);
        getRedisTemplate().expire("WarehouseDev:"+warehouseId, 259200, TimeUnit.SECONDS);
         // Setting expire directly on the key
        put(warehouseId, data);
    }
    public List<Object> getDataByTimestampRange(String warehouseId, long startTimestamp, long endTimestamp) {
//        String key = warehouseId;
        boolean exists = getRedisTemplate().hasKey("WarehouseDev:"+warehouseId);
        DataType keyType = getRedisTemplate().type("WarehouseDev:"+warehouseId);

//        Long size = getRedisTemplate().opsForZSet().size(key);
        Set<Object> dataInRange = getRedisTemplate().opsForZSet().rangeByScore("WarehouseDev:"+warehouseId, startTimestamp, endTimestamp);
//        getRedisTemplate().opsForZSet().rangeByScoreWithScores(key, startTimestamp, endTimestamp)


//        Set<Object> dataInRange1= getRedisTemplate().opsForZSet ().reverseRange(key, startTimestamp, endTimestamp);
        return new ArrayList<>(dataInRange);
    }

//    public void setValueWithExpiration(String key, HumidityAndtemperature value, long expirationSeconds) {
//        getRedisTemplate().opsForValue().set(key, value, expirationSeconds, TimeUnit.SECONDS);
//    }
}
