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); }
import io from 'socket.io-client';
import { load, USER } from "../utils/MyAsyncStorage";
import listChatStore from "../screens/listchat/ListChatStore";
import chatStore from "../screens/chat/ChatStore";
import { Log } from "../utils";
import { runInAction, toJS } from "mobx";
import appStore from "../screens/AppStore";
import { AppState } from "react-native";
import _ from "lodash";
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 => {
      console.log('socket', event);
      try {
        var _event$message7;
        let handled = false;
        const right = (event === null || event === void 0 ? void 0 : event.message.sender) === appStore.user.type + '_' + appStore.user.user_id;
        try {
          runInAction(() => {
            let messageIdx = 0;
            listChatStore.dataPin = [...listChatStore.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.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.dataPin, messageIdx, 0);
            listChatStore.dataPin = [...listChatStore.dataPin];
          });
        } catch (e) {
          console.log(e);
        }

        //Handler conversation
        try {
          runInAction(() => {
            let messageIdx = 0;
            listChatStore.data = listChatStore.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.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.data, messageIdx, 0);
            listChatStore.data = [...listChatStore.data];
          });
        } catch (e) {
          console.log(e);
        }

        //Handler message

        if (chatStore.conversation_id === ((_event$message7 = event.message) === null || _event$message7 === void 0 ? void 0 : _event$message7.conversation_id)) {
          const message = chatStore.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) {
            runInAction(() => {
              chatStore.data = [event.message, ...chatStore.data];
              chatStore.data = [...chatStore.data];
            });
          }
        }
        if (!handled) {
          runInAction(() => {
            listChatStore.data = _.unionBy([event], listChatStore.data, '_id');
          });
        }
      } catch (e) {
        Log(e);
      }
    });
    _defineProperty(this, "onUserReactionMessage", event => {
      try {
        if (chatStore.conversation_id === event.conversation._id) {
          chatStore.data = chatStore.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.conversation_id === event.conversation._id) {
          chatStore.data = chatStore.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 {
        runInAction(() => {
          listChatStore.dataPin = [...listChatStore.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.dataPin = [...listChatStore.dataPin];
        });
      } catch (e) {
        console.log(e);
      }

      //Handler conversation
      try {
        runInAction(() => {
          listChatStore.data = listChatStore.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.data = [...listChatStore.data];
        });
      } catch (e) {
        console.log(e);
      }
    });
  }
  async init() {
    const user = await load(USER);
    if (user && this.currentToken !== user.token) {
      this.socket = io.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);
export default Socket;
//# sourceMappingURL=index.js.map