package com.yeejoin.amos.boot.module.common.biz.refresh.adapter;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.common.api.constant.TZSCommonConstant;
import lombok.RequiredArgsConstructor;
import org.eclipse.paho.client.mqttv3.MqttMessage;
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.nio.charset.StandardCharsets;
import java.util.List;

@Component
@RequiredArgsConstructor
public class Emq2DataRefreshEvent extends EmqxListener {

    private final EmqKeeper emqKeeper;


    @Value("${spring.application.name}")
    private String applicationName;

    private final DataRefreshEventBuilderService dataRefreshEventBuilderService;

    @Override
    public void processMessage(String topic, MqttMessage message) {
        byte[] payload = message.getPayload();
        String str = new String(payload, StandardCharsets.UTF_8);
        List<String> records = JSONObject.parseArray(str, String.class);
        dataRefreshEventBuilderService.processMessage(topic, records);
    }

    @PostConstruct
    void init() throws Exception {
        String topic = TZSCommonConstant.DATA_REFRESH_TOPIC.replace("%s", "+");
        emqKeeper.subscript(this.buildShareTopic(topic), 2, this);
    }

    private String buildShareTopic(String topic) {
        return "$share/" + applicationName + "/" + topic;
    }
}
