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

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

    async consume(topic: string, version: number, baseEventHandler: BaseEventHandler) {
        await this.consumeFromMaster(topic, version, baseEventHandler)
    }

    private async consumeFromMaster(topic: string, version: number, baseEventHandler: BaseEventHandler) {
        let subscriptionId = process.env['KT_SUBSCRIPTION_ID'];
        let client: Client = await this.pulsarMasterFactory.get();
        await client.subscribe({
            topic: topic,
            subscription: `${subscriptionId}-${version}`,
            subscriptionType: 'Shared',
            listener: async (msg, msgConsumer) => {
                const currentVersion: number = msg.getProperties()["version"];
                try {
                    await baseEventHandler.handle(msg.getData())
                    msgConsumer.acknowledge(msg);
                } catch (e) {
                    console.log('执行事件处理器发生异常:' + e)
                }
                // if (currentVersion === version) {

                // }
            },
        });
    }
}