package com.yzt.airconditionersystem.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yzt.airconditionersystem.config.MqttOutboundConfig;
import com.yzt.airconditionersystem.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author TzZach
 * @since 2022-05-10 21:20
 */
@Controller
@Slf4j
public class MqttController {

    @Autowired
    private MqttOutboundConfig.MyGateway mqttGateway;
    @Autowired
    private MessageHandler mqttOutbound;

//    @Autowired
//    private MqttProducer mqttProducer;
//
//    @PostMapping("/send")
//    @ResponseBody
//    public Result send(String topic, String data) {
//
//        log.info("开始发送mqtt消息,主题：{},消息：{}", topic, data);
//        if (StringUtils.isNotBlank(topic)) {
//            mqttProducer.send(topic, data);
//            log.info("发送mqtt消息完成,主题：{},消息：{}", topic, data);
//            return Result.success("execute successful");
//        } else {
//            return Result.error("topic is blank");
//        }
//    }

    @PostMapping("/send")
    @ResponseBody
    public Result send(String topic, String data) {

        log.info("开始发送mqtt消息,主题：{},消息：{}", topic, data);
        if (StringUtils.isNotBlank(topic)) {
//            mqttProducer.send(topic, data);
            ((MqttPahoMessageHandler) mqttOutbound).setDefaultTopic(topic);
            mqttGateway.sendToMqtt(data);
            log.info("发送mqtt消息完成,主题：{},消息：{}", topic, data);
            return Result.success("execute successful");
        } else {
            return Result.error("topic is blank");
        }
    }
}
