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

@Singleton
class PulsarSlaveFactory {
  private client: Client;

  private producerMap = new Map();

  async init() {
    if (this.client) {
      return;
    }
    this.client = await new Client({
      serviceUrl: `pulsar://101.37.145.159:6650`,
    });

    Container.bind(Client).factory(() => {
      let pulsarSlaveFactory = Container.get(PulsarSlaveFactory);
      return pulsarSlaveFactory.get();
    }).scope(Scope.Singleton);
  }

  get(): Client {
    return this.client;
  }

  /**
   * pulsar生产者
   */
  async getProducerByTopic(topic: String): Producer {
    if (this.producerMap.has(topic)) {
      return this.producerMap.get(topic);
    }
    let producer = await this.get().createProducer({
      topic: topic,
    });
    this.producerMap.set(topic, producer);
    return producer;
  }
}

export { PulsarSlaveFactory, Client, Producer }