package com.yeejoin.amos.message.eqmx;

import com.alibaba.fastjson.JSON;
import com.yeejoin.amos.message.kafka.KafkaProducerService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
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.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import static com.alibaba.fastjson.JSON.parseArray;

@Slf4j
@Component
public class EmqMessageService  extends EmqxListener {


    @Autowired
    protected EmqKeeper emqKeeper;

    @Autowired
    protected KafkaProducerService kafkaProducerService;

    @Value("classpath:/json/topic.json")
    private Resource topic;

    private List<Map> list;

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


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

    @PostConstruct
    void init()  {
        new Thread(task_runnable).start();

        String json = null;
        try {
            json = IOUtils.toString(topic.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }

        list = parseArray(json, Map.class);

        String[] split = topics.split(",");
        Arrays.stream(split).forEach(e-> {
            try {
                emqKeeper.subscript(e, 1, this);
            } catch (Exception exception) {
                log.info("订阅eqm消息失败 ====> 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");
                    // 处理逻辑
                    list.forEach(e->{
                        if (e.get("emqTopic").toString().equals(messageResult.getString("topic"))) {
                            kafkaProducerService.sendMessageAsync(e.get("akkaTopic").toString(),JSON.toJSONString(result));
                        }
                    });
                } catch (Exception e) {
                    Thread.currentThread().interrupt();
                    log.info("发送kafka消息失败 ====> message: {}", e.getMessage());
                }
            }
        }
    };
}
