import config from "config";
import SocketIO from "socket.io";

import ticketNs from './ticket.ws';

const NAMESPACES = [
  ticketNs
];

export class WsServer {

  private socket: SocketIO.Server = new SocketIO(config.get('wsPort'));

  private lastConnectedUser: string | undefined;

  public init() {
    console.info('WsServer initialized');
    this.initNamespaces();
  }

  private initNamespaces() {
    for (const ns of NAMESPACES) {
      if (typeof ns.init != 'function') {
        throw new Error('[WebSocket] Failed to initialize namespace - `init` method is missing');
      }

      ns.init(this.createNamespace(ns.NAMESPACE_NAME));
    }
  }

  public postMessage(message: string) {
    console.log('tru post message');
    if (this.lastConnectedUser == null) {
      return;
    }
    console.log('message posted');

    this.socket.to(this.lastConnectedUser).emit('message', `Message sent: ${message}`);
  }

  public createNamespace(name: string): SocketIO.Namespace {
    return this.socket.of(`/${name}`);
  }

}

export default new WsServer();
