import {IoAdapter} from "@nestjs/platform-socket.io";
import {createAdapter} from "@socket.io/mongo-adapter";
import {ServerOptions} from "socket.io";
import {MongoClient} from "mongodb";
import {Emitter} from "@socket.io/mongo-emitter";
import {ConfigService} from "@nestjs/config";

const DB = "socket-io";
const COLLECTION = "socket.io-adapter-events";

export class MongoIoAdapter extends IoAdapter{
  private adapterConstructor: ReturnType<typeof createAdapter>;
  private mongoClient: MongoClient;
  async connectToMongo(configService: ConfigService): Promise<void> {
    this.mongoClient = new MongoClient(configService.get<string>('MONGO_URL'));
    await this.mongoClient.connect();
    try {
      await this.mongoClient.db(DB).createCollection(COLLECTION, {
        capped: true,
        size: 1e6
      });
    } catch (e) {
      // collection already exists
    }

    const mongoCollection = this.mongoClient.db(DB).collection(COLLECTION);
    const emitter = new Emitter(mongoCollection);

    // setInterval(() => {
    //   // emitter.emit("events", new Date());
    //   // console.log(`emit ping`);
    // }, 1000);
    this.adapterConstructor = createAdapter(mongoCollection);
  }
  createIOServer(port: number, options?: ServerOptions): any {
    const server = super.createIOServer(port, options);
    server.adapter(this.adapterConstructor);
    return server;
  }
}