package com.yeejoin.equip.eqmx;

import com.alibaba.fastjson.JSON;
import com.yeejoin.equip.kafka.KafkaProducerService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.component.emq.EmqxListener;
import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author LiuLin
 * @date 2023/6/25
 * @apiNote Emq消息转发Kafka
 */
@Slf4j
@Component
public class EmqMessageService extends EmqxListener {

    @Autowired
    protected EmqKeeper emqKeeper;

    @Autowired
    protected KafkaProducerService kafkaProducerService;

    @Value("${emq.topic}")
    private String emqTopic;

    @Value("${kafka.topic}")
    private String kafkaTopic;

    private static final BlockingQueue<JSONObject> blockingQueue = new LinkedBlockingQueue<>();

    @PostConstruct
    void init()  {
        new Thread(task_runnable).start();
        String[] split = emqTopic.split(",");
        Arrays.stream(split).forEach(e-> {
            try {
                emqKeeper.subscript(e, 1, this);
            } catch (Exception exception) {
                log.info("订阅emq消息失败 ====> message: {}", exception.getMessage());
            }
        });
    }

    @Override
    public void processMessage(String topic, MqttMessage message) throws Exception {
        JSONObject result = JSONObject.fromObject(new String(message.getPayload()));
        JSONObject messageResult = new JSONObject();
        messageResult.put("result", result);
        messageResult.put("topic", topic);
        blockingQueue.add(messageResult);
    }

    Runnable task_runnable = new Runnable() {
        public void run() {
            int k = 0;
            boolean b = true;
            while (b) {
                k++;
                b = k < Integer.MAX_VALUE;
                try {
                    JSONObject messageResult = blockingQueue.take();
                    JSONObject result = messageResult.getJSONObject("result");
                    if ((messageResult.getString("topic")).equals(emqTopic)) {
                        kafkaProducerService.sendMessageAsync(kafkaTopic,JSON.toJSONString(result));
                    }
                } catch (Exception e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    };
}
