package com.casic.missiles.modular.system.rs;

import com.casic.missiles.modular.system.dto.CommConfigDTO;
import com.casic.missiles.modular.system.model.Device;
import com.casic.missiles.modular.system.service.IBusConfigService;
import com.casic.missiles.modular.system.service.IDeviceService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Created by test203 on 2019/5/30.
 */
@Service
public class RedisCommon {

    @Autowired
    protected RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IDeviceService iDeviceService;

    @Qualifier("busConfigServiceImpl")
    @Autowired
    private IBusConfigService iBusConfigService;

    @Value("${smartcity.device.redis.invalid-time}")
    private String invalidTime;
    @Value("${smartcity.device.redis.config-prefix}")
    private String configPrefix;

    public String sendMsg(String devType, Long devId, String str, String attemptsMax) {
        AbstractRequest abstractRequest = AbstractRequest.abstractRequestHashMap.get(devType);
        String concenCode=iBusConfigService.getConcenCodeByDevId(devId);
        Device device = iDeviceService.selectById(devId);
        if (null != device) {
            abstractRequest.setConcentratorCode(concenCode);
            abstractRequest.send(device.getDevcode(), str, attemptsMax);
        }
        return abstractRequest.getConcentratorCode();

    }

    public void setRedisConcentrator(String concentratorcode, String devcode, String attemptsMax) {
        redisTemplate.opsForList().leftPush(configPrefix + concentratorcode,
                devcode + ":" + (StringUtils.isNotBlank(attemptsMax) && (!("--".equals(attemptsMax))) ? attemptsMax : "1"));
    }

    public void setRedisConfig(String key, CommConfigDTO commConfigDTO) {
//        Gson g = new GsonBuilder().serializeNulls().create();

        Gson g = new GsonBuilder().create();
        redisTemplate.opsForValue().set(configPrefix+ key,
                g.toJson(commConfigDTO),
                Integer.valueOf(invalidTime),
                TimeUnit.SECONDS);
    }

    public void setRightRedisConcentrator(String concentratorcode, String devcode) {
        redisTemplate.opsForList().rightPush(configPrefix + concentratorcode, "$" + devcode);
    }
}
