"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ClientLobby = void 0;
var _socket = require("socket.io-client");
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
class ClientLobby {
  constructor() {
    let {
      url,
      channelId,
      session = {}
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    this.url = url || process.env.SERVICE_LOBBY || (typeof window !== 'undefined' ? "".concat(window.location.protocol, "//").concat(window.location.hostname, ":4000") : 'http://localhost:4000');
    this.fingerprint = localStorage.getItem('MIRAI:FINGERPRINT') || "chat-".concat(Date.now());
    this.channelId = channelId;
    if (!this.channelId) throw new Error('channelId es obligatorio');
    this.title = session !== null && session !== void 0 && session.firstName ? "".concat(session.firstName, " ").concat(session.lastName || '').trim() : (session === null || session === void 0 ? void 0 : session.email) || "Guest ".concat(this.fingerprint);
    this.session = session;
    this.socket = null;
    this.chatId = this.fingerprint;
    this.callbacks = {
      message: [],
      blockState: [],
      presence: [],
      status: []
    };
    this.aiBlocked = false;
    this.lastPresence = null;
  }
  onMessage(cb) {
    this.callbacks.message.push(cb);
    return () => this.off('message', cb);
  }
  onBlockState(cb) {
    this.callbacks.blockState.push(cb);
    return () => this.off('blockState', cb);
  }
  onPresence(cb) {
    this.callbacks.presence.push(cb);
    return () => this.off('presence', cb);
  }
  onStatus(cb) {
    this.callbacks.status.push(cb);
    return () => this.off('status', cb);
  }
  off(type, cb) {
    this.callbacks[type] = (this.callbacks[type] || []).filter(fn => fn !== cb);
  }
  _emit(type, payload) {
    (this.callbacks[type] || []).forEach(cb => cb(payload));
  }
  connect() {
    var _this = this;
    if (this.socket) return;
    this.socket = (0, _socket.io)(this.url.replace('/lobby', ''), {
      auth: {
        fingerprint: this.fingerprint,
        channelId: this.channelId,
        session: this.session
      },
      path: '/lobby/socket.io'
    });
    this._emit('status', 'connecting');
    this.socket.on('connect', () => {
      this._emit('status', 'connected');
      this.socket.emit('join_chat', {
        chatId: this.chatId,
        title: this.title,
        fingerprint: this.fingerprint,
        channelId: this.channelId,
        session: this.session
      });
    });
    this.socket.on('disconnect', () => {
      this._emit('status', 'disconnected');
      this.socket = null;
    });
    this.socket.on('message', msg => {
      var _msg$createdAt;
      this._emit('message', _objectSpread(_objectSpread({}, msg), {}, {
        createdAt: (_msg$createdAt = msg.createdAt) !== null && _msg$createdAt !== void 0 ? _msg$createdAt : Date.now()
      }));
    });
    this.socket.on('ai_block_state', _ref => {
      let {
        chatId,
        fingerprint,
        blocked
      } = _ref;
      if (chatId === this.chatId || fingerprint === this.fingerprint) {
        if (this.aiBlocked !== blocked) {
          this.aiBlocked = blocked;
          this._emit('blockState', blocked);
        }
      }
    });
    this.socket.on('presence', _ref2 => {
      let {
        chatId,
        online
      } = _ref2;
      if (chatId === this.chatId) {
        if (this.lastPresence !== online) {
          this.lastPresence = online;
          this._emit('presence', online);
        }
      }
    });
    this.socket.on('presence_snapshot', function () {
      let snapshot = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      const online = snapshot[_this.chatId];
      if (online !== undefined && online !== _this.lastPresence) {
        _this.lastPresence = online;
        _this._emit('presence', online);
      }
    });
  }
  disconnect() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
      this._emit('status', 'disconnected');
    }
  }
  requestHumanSupport() {
    if (!this.socket) return;
    this.socket.emit('request_human_support', {
      chatId: this.chatId,
      channelId: this.channelId,
      fingerprint: this.fingerprint
    });
  }
  send(_ref3) {
    let {
      body,
      author = 'user'
    } = _ref3;
    if (!this.socket) return;
    if (author === 'ai' && this.aiBlocked) return;
    this.socket.emit('message', {
      chatId: this.chatId,
      body,
      author,
      session: this.session,
      channelId: this.channelId,
      fingerprint: this.fingerprint
    });
  }
}
exports.ClientLobby = ClientLobby;
//# sourceMappingURL=clientLobby.js.map