import { Client, Producer, Message, MessageId } from "pulsar-client";
import { Container, Scope, Singleton, Inject } from "typescript-ioc";
import { PulsarMasterFactory } from "../PulsarMasterFactory";
import { EventHandler } from "./EventHandler";

@Singleton
export class Consumer {
    @Inject
    private pulsarMasterFactory: PulsarMasterFactory;

    async startConsumer(topic: string, version: string, eventHandler: EventHandler) {
        await this.consumeFromMaster(topic, version, eventHandler)
    }

    async consumeFromMaster(topic: string, version: string, eventHandler: EventHandler) {
        let deployId = process.env['KT_DEPLOY_ID'];
        let client: Client = await this.pulsarMasterFactory.get();
        await client.subscribe({
            topic: topic,
            subscription: deployId,
            subscriptionType: 'Shared',
            listener: async (msg, msgConsumer) => {
                const currentVersion = msg.getProperties()["version"];
                if (currentVersion === version) {
                    try {
                        await eventHandler.handle(msg.getData().toString())
                        msgConsumer.acknowledge(msg);
                    } catch (e) {
                        console.log('执行事件处理器发生异常:' + e)
                    }
                }
            },
        });
    }
}