"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _socket = _interopRequireDefault(require("socket.io-client"));
var _MyAsyncStorage = require("../utils/MyAsyncStorage");
var _ListChatStore = _interopRequireDefault(require("../screens/listchat/ListChatStore"));
var _ChatStore = _interopRequireDefault(require("../screens/chat/ChatStore"));
var _utils = require("../utils");
var _mobx = require("mobx");
var _AppStore = _interopRequireDefault(require("../screens/AppStore"));
var _reactNative = require("react-native");
var _lodash = _interopRequireDefault(require("lodash"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
class Socket {
  arraymove(arr, fromIndex, toIndex) {
    try {
      if (fromIndex !== toIndex) {
        var element = arr[fromIndex];
        arr.splice(fromIndex, 1);
        arr.splice(toIndex, 0, element);
      }
    } catch (e) {
      console.log(e);
    }
  }
  static getInstance() {
    if (Socket.instance !== undefined) {
      return Socket.instance;
    } else {
      Socket.instance = new Socket();
      return Socket.instance;
    }
  }
  constructor() {
    _defineProperty(this, "URL", 'https://stag-receiverchat.viettelpost.vn');
    _defineProperty(this, "socket", void 0);
    _defineProperty(this, "currentToken", void 0);
    _defineProperty(this, "hasDisconnect", void 0);
    _defineProperty(this, "onConnect", () => {
      this.socket.on('USER_MESSAGE', this.onUserMessage);
      this.socket.on('USER_STATE', this.onUserStateMessage);
      this.socket.on('USER_REACT_MESSAGE', this.onUserReactionMessage);
      this.socket.on('USER_READ_MESSAGE', this.onUserReadMessage);
      try {
        // if(this.hasDisconnect){
        //   this.hasDisconnect = false
        //   listChatStore.getDataBackground();
        //   if(chatStore.conversation_id){
        //     chatStore.getDataBackground()
        //   }
        // }
      } catch (e) {
        console.log(e);
      }
    });
    _defineProperty(this, "onDisconnect", () => {
      this.hasDisconnect = true;
    });
    _defineProperty(this, "onUserMessage", event => {
      try {
        var _event$message7;
        let handled = false;
        const right = (event === null || event === void 0 ? void 0 : event.message.sender) === _AppStore.default.user.type + '_' + _AppStore.default.user.user_id;
        try {
          (0, _mobx.runInAction)(() => {
            let messageIdx = 0;
            _ListChatStore.default.dataPin = [..._ListChatStore.default.dataPin.map((c, index) => {
              var _event$message, _event$message2;
              if (c._id === (event === null || event === void 0 ? void 0 : (_event$message = event.message) === null || _event$message === void 0 ? void 0 : _event$message.conversation_id) && c.message._id !== (event === null || event === void 0 ? void 0 : (_event$message2 = event.message) === null || _event$message2 === void 0 ? void 0 : _event$message2._id)) {
                var _event$message3;
                if (!right && _ChatStore.default.conversation_id !== (event === null || event === void 0 ? void 0 : (_event$message3 = event.message) === null || _event$message3 === void 0 ? void 0 : _event$message3.conversation_id)) {
                  c.settings = c.settings.map(setting => {
                    setting.unread_count += 1;
                    return setting;
                  });
                }
                c.message = event.message;
                messageIdx = index;
                handled = true;
              }
              return c;
            })];
            this.arraymove(_ListChatStore.default.dataPin, messageIdx, 0);
            _ListChatStore.default.dataPin = [..._ListChatStore.default.dataPin];
          });
        } catch (e) {
          console.log(e);
        }

        //Handler conversation
        try {
          (0, _mobx.runInAction)(() => {
            let messageIdx = 0;
            _ListChatStore.default.data = _ListChatStore.default.data.map((c, index) => {
              var _event$message4, _event$message5;
              if (c._id === (event === null || event === void 0 ? void 0 : (_event$message4 = event.message) === null || _event$message4 === void 0 ? void 0 : _event$message4.conversation_id) && c.message._id !== (event === null || event === void 0 ? void 0 : (_event$message5 = event.message) === null || _event$message5 === void 0 ? void 0 : _event$message5._id)) {
                var _event$message6;
                if (!right && _ChatStore.default.conversation_id !== (event === null || event === void 0 ? void 0 : (_event$message6 = event.message) === null || _event$message6 === void 0 ? void 0 : _event$message6.conversation_id)) {
                  c.settings = c.settings.map(setting => {
                    setting.unread_count += 1;
                    return setting;
                  });
                }
                messageIdx = index;
                c.message = event.message;
                handled = true;
              }
              return c;
            });
            this.arraymove(_ListChatStore.default.data, messageIdx, 0);
            _ListChatStore.default.data = [..._ListChatStore.default.data];
          });
        } catch (e) {
          console.log(e);
        }

        //Handler message

        if (_ChatStore.default.conversation_id === ((_event$message7 = event.message) === null || _event$message7 === void 0 ? void 0 : _event$message7.conversation_id)) {
          const message = _ChatStore.default.data.find(m => {
            var _event$message8;
            return m._id === (event === null || event === void 0 ? void 0 : (_event$message8 = event.message) === null || _event$message8 === void 0 ? void 0 : _event$message8._id);
          });
          if (!message && !right) {
            (0, _mobx.runInAction)(() => {
              _ChatStore.default.data = [event.message, ..._ChatStore.default.data];
              _ChatStore.default.data = [..._ChatStore.default.data];
            });
          }
        }
        if (!handled) {
          (0, _mobx.runInAction)(() => {
            _ListChatStore.default.data = [event, ..._ListChatStore.default.data];
          });
        }
      } catch (e) {
        (0, _utils.Log)(e);
      }
    });
    _defineProperty(this, "onUserReactionMessage", event => {
      try {
        if (_ChatStore.default.conversation_id === event.conversation._id) {
          _ChatStore.default.data = _ChatStore.default.data.map(m => {
            if (m._id === event.conversation.message._id) {
              m.reactions = event.conversation.message.reactions;
            }
            return m;
          });
        }
      } catch (e) {}
    });
    _defineProperty(this, "onUserReadMessage", event => {
      try {
        if (_ChatStore.default.conversation_id === event.conversation._id) {
          _ChatStore.default.data = _ChatStore.default.data.map(m => {
            if (m._id === event.conversation.message._id) {
              m.read_by = event.conversation.message.read_by;
            }
            return m;
          });
        }
      } catch (e) {}
    });
    _defineProperty(this, "onUserStateMessage", event => {
      try {
        (0, _mobx.runInAction)(() => {
          _ListChatStore.default.dataPin = [..._ListChatStore.default.dataPin.map(c => {
            if (c.sender === (event === null || event === void 0 ? void 0 : event.full_user_id)) {
              c.detail_participants = c.detail_participants.map(pa => {
                if (pa.full_user_id === event.full_user_id) {
                  pa['state'] = [event.state];
                }
                return pa;
              });
            }
            return c;
          })];
          _ListChatStore.default.dataPin = [..._ListChatStore.default.dataPin];
        });
      } catch (e) {
        console.log(e);
      }

      //Handler conversation
      try {
        (0, _mobx.runInAction)(() => {
          _ListChatStore.default.data = _ListChatStore.default.data.map(c => {
            if (c.sender === (event === null || event === void 0 ? void 0 : event.full_user_id)) {
              c.detail_participants = c.detail_participants.map(pa => {
                if (pa.full_user_id === event.full_user_id) {
                  pa['state'] = [event.state];
                }
                console.log('pa', pa);
                return pa;
              });
            }
            return c;
          });
          _ListChatStore.default.data = [..._ListChatStore.default.data];
        });
      } catch (e) {
        console.log(e);
      }
    });
  }
  async init() {
    const user = await (0, _MyAsyncStorage.load)(_MyAsyncStorage.USER);
    if (user && this.currentToken !== user.token) {
      this.socket = _socket.default.connect(this.URL, {
        reconnection: true,
        autoConnect: true,
        transports: ["polling", "websocket", "webtransport"],
        extraHeaders: {
          Authorization: user.token
        }
      });
      this.currentToken = user.token;
      this.socket.on('connect', this.onConnect);
      this.socket.on('disconnect', this.onDisconnect);
    } else {
      // alert('Kết nối Socket ko thành công.')
    }
  }
}
_defineProperty(Socket, "instance", void 0);
var _default = Socket;
exports.default = _default;
//# sourceMappingURL=index.js.map