import { Payload } from "../model/Payload";
import { Client, Producer, Message, MessageId } from "pulsar-client";
import { Container, Scope, Singleton, Inject } from "typescript-ioc";
import { PulsarMasterFactory } from "../pulsar/PulsarMasterFactory";
import { PulsarSlaveFactory } from "../pulsar/PulsarSlaveFactory";
import { Config } from "../config/Config";

export class Publisher {
    @Inject
    private pulsarMasterFactory: PulsarMasterFactory;

    @Inject
    private pulsarSlaveFactory: PulsarSlaveFactory;

    /**
     * 发送主pulsar
     */
    async publishToMaster(payload: Payload) {
        let defaultTopic: string = `persistent://${Config.getDefaultTenant()}/${Config.getDefaultNamespace()}/${payload.getTopic()}`;
        let producer: Producer = await this.pulsarMasterFactory.getProducerByTopic(defaultTopic);
        await this.sendMsgToPulsar(payload, producer);
    }

    /**
    * 发送备pulsar
    */
    async publishToSlave(payload: Payload) {
        let defaultTopic: string = `persistent://${Config.getDefaultTenant()}/${Config.getDefaultNamespace()}/${payload.getTopic()}`;
        let producer: Producer = await this.pulsarSlaveFactory.getProducerByTopic(defaultTopic)
        await this.sendMsgToPulsar(payload, producer);
    }

    /**
     * 执行发送
     * @param payload 
     * @param producer 
     */
    private async sendMsgToPulsar(payload: Payload, producer: Producer) {
        const msg = JSON.stringify(payload);
        console.log("开始发送pulsar数据:" + msg);
        await producer.send({
            data: Buffer.from(msg),
            properties: {
                'version': payload.getVersion()
            }
        });
        console.log("发送pulsar数据成功！");
    }
}