package net.northking.cctp.device.bus.publisher;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.device.bus.BusConstants;
import net.northking.cctp.device.bus.publisher.dto.ConsumerInfoDto;
import net.northking.cctp.device.constants.DeviceError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@Component
public class CtrlMQPublisher implements CtrlPublisher {

    private final static Logger logger = LoggerFactory.getLogger(CtrlMQPublisher.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public void restartCtrl(String uuid) {
        ConsumerInfoDto dto = new ConsumerInfoDto();
        dto.setCtrlId(uuid);
        dto.setType("0");
        byte[] json;
        String data = JSON.toJSONString(dto);
        Message message = null;
        try {
            message = new Message(data.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new PlatformRuntimeException(DeviceError.MQ_PUBLISHER_ERR);
        }
        logger.info("--------------------------重启上位机:"+ uuid+ "--------------------------");
        amqpTemplate.convertAndSend(BusConstants.Ctrl_Restart_Exchange,uuid,message);
    }

    @Override
    public void restartDeviceList(List<Map<String, String>> deviceList, String uuid) {
        //批量重启设备
        ConsumerInfoDto dto = new ConsumerInfoDto();
        dto.setType("3");
        dto.setDeviceList(deviceList);
        String data = JSON.toJSONString(dto);
        Message message = null;
        try {
            message = new Message(data.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new PlatformRuntimeException(DeviceError.MQ_PUBLISHER_ERR);
        }
        logger.info("--------------------------重启设备:{}",data);
        amqpTemplate.convertAndSend(BusConstants.Ctrl_Restart_Exchange,uuid,message);
    }


}
