import { Payload } from "./model/Payload";
import { Event } from "./model/Event";
import { Client, Producer, Message, MessageId } from "pulsar-client";

class EcPublisher {

    private pulsarClientArray: Array<Client>

    private pulsarProducerMap = new Map();

    private pulsarProducerArray: Array<Producer>

    constructor() {
        //todo 定时拉取注册中心作缓存
        let pulsarClients = new Array();
        const client = new Client({
            serviceUrl: 'pulsar://101.37.145.159:6650',
        });
        pulsarClients.push(client);
        this.pulsarClientArray = pulsarClients;

        // //todo 拉取注册中心看目前总公共有多少个目标环境
        // let pulsarProducers = new Array();
        // const producer = client.createProducer({
        //     topic: 'persistent://yongqiangTenant/yongqiangNamespace/' + Event.getTopic(),
        // }).then(() =>
        //     pulsarProducers.push(producer)
        // );
        // this.pulsarProducerArray = pulsarProducers;
    }

    publishMessage(payloadSchema: Payload, sendType: String) {
        // this.pulsarProducerArray.forEach(producer => {
        //     const msg = JSON.stringify(payloadSchema);
        //     console.log("开始发送pulsar数据:" + msg);
        //     producer.send({
        //         data: Buffer.from(msg),
        //     });
        //     console.log("发送pulsar数据成功！");
        // });

        this.pulsarClientArray.forEach(client => {
            (async () => {
                let topic = 'persistent://yongqiangTenant/yongqiangNamespace/' + Event.getTopic();
                let producer = this.pulsarProducerMap.get(topic);
                if (producer == undefined) {
                    console.log("当前生产者为undefined...");
                    producer = await client.createProducer({
                        topic: topic,
                    });
                    this.pulsarProducerMap.set(topic, producer);
                } else {
                    console.log("当前生产者正常...");
                }

                const msg = JSON.stringify(payloadSchema);
                console.log("开始发送pulsar数据:" + msg);
                producer.send({
                    data: Buffer.from(msg),
                });
                console.log("发送pulsar数据成功！");
            })();
        });
    }
}

export { EcPublisher }