"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = require("react");
var _reactRedux = require("react-redux");
var _xmppProvider = require("../context/xmppProvider");
var _chatAutoEnterer = require("../helpers/chatAutoEnterer");
var _initRoomsPresence = require("../helpers/initRoomsPresence");
var _updatedChatLastTimestamps = require("../helpers/updatedChatLastTimestamps");
var _updateMessagesTillLast = require("../helpers/updateMessagesTillLast");
var _apiClient = require("../networking/apiClient");
var _chatSettingsSlice = require("../roomStore/chatSettingsSlice");
var _roomsSlice = require("../roomStore/roomsSlice");
var _useRoomState = require("./useRoomState");
var _useChatSettingState = require("./useChatSettingState");
var _isChatIdPresentInArray = require("../helpers/isChatIdPresentInArray");
var _useGetNewArchRoom = _interopRequireDefault(require("./useGetNewArchRoom"));
var _getRoomsWithRetry = require("../helpers/getRoomsWithRetry");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/** @format */

const useChatWrapperInit = ({
  roomJID,
  wasAutoSelected,
  config
}) => {
  const dispatch = (0, _reactRedux.useDispatch)();
  const [inited, setInited] = (0, _react.useState)(false);
  const [showModal, setShowModal] = (0, _react.useState)(false);
  const [isConnectionLost, setConnectionLost] = (0, _react.useState)(false);
  const [isRetrying, setIsRetrying] = (0, _react.useState)(false);
  const hasSyncedHistoryRef = (0, _react.useRef)(false);
  const {
    client,
    initializeClient,
    setClient
  } = (0, _xmppProvider.useXmppClient)();
  const syncRooms = (0, _useGetNewArchRoom.default)();
  const {
    rooms
  } = (0, _reactRedux.useSelector)(state => state.rooms);
  const {
    roomsList
  } = (0, _useRoomState.useRoomState)();
  const {
    user
  } = (0, _useChatSettingState.useChatSettingState)();
  (0, _react.useEffect)(() => {
    return () => {
      if (client && user.xmppPassword === '') {
        console.log('closing client');
        client.close();
        setClient(null);
      }
    };
  }, [user.xmppPassword]);
  const getRoomsWithRertyRequest = async () => {
    setIsRetrying(true);
    const retryRooms = await (0, _getRoomsWithRetry.getRoomsWithRetry)(client, config, syncRooms, roomJID);
    if (!retryRooms) {
      setIsRetrying('norooms');
      return;
    }
    setIsRetrying(false);
  };
  const loadRooms = async (client, disableLoad = false) => {
    !disableLoad && dispatch((0, _roomsSlice.setIsLoading)({
      loading: true,
      loadingText: 'Loading rooms...'
    }));
    const rooms = await syncRooms(client, config);
    dispatch((0, _roomsSlice.setIsLoading)({
      loading: false,
      loadingText: undefined
    }));
    return rooms;
  };
  (0, _react.useEffect)(() => {
    let retryTimeout;
    const initXmmpClient = async () => {
      if (config?.translates?.enabled && !config?.translates?.translations) {
        dispatch((0, _chatSettingsSlice.setLangSource)(config?.translates?.translations));
      }
      dispatch((0, _chatSettingsSlice.setConfig)(config));
      try {
        if (!user.xmppUsername) {
          setShowModal(true);
          console.error('Error, no user');
        } else {
          (0, _chatAutoEnterer.chatAutoEnterer)({
            roomJID,
            wasAutoSelected,
            config,
            dispatch
          });
          if (!client) {
            try {
              setInited(false);
              setShowModal(false);
              console.log(' No client, initializing one');
              const newClient = await initializeClient(user.xmppUsername || user?.defaultWallet?.walletAddress, user?.xmppPassword, config?.xmppSettings);
              console.log(' Client initialized', newClient?.status);
              if (roomsList && Object.keys(roomsList).length > 0) {
                console.log(' Using existing roomsList', Object.keys(roomsList).length);
                setInited(true);
                await (0, _initRoomsPresence.initRoomsPresence)(newClient, roomsList);
              } else {
                if (config?.newArch) {
                  console.log(' Loading rooms with newArch');
                  const loadedRooms = await loadRooms(newClient);
                  console.log(' Loaded rooms', loadedRooms?.length || 0);
                  if (config?.enableRoomsRetry?.enabled) {
                    const isSelectedRoomPresent = (0, _isChatIdPresentInArray.isChatIdPresentInArray)(roomJID, loadedRooms);
                    console.log(' Selected room present?', isSelectedRoomPresent, roomJID);
                    if (!isSelectedRoomPresent) {
                      await getRoomsWithRertyRequest();
                    }
                  }
                  setInited(true);
                } else {
                  console.log(' Using old arch, getting rooms stanza');
                  await newClient.getRoomsStanza();
                }
              }
              try {
                const roomTimestampObject = await newClient.getChatsPrivateStoreRequestStanza();
                console.log('Got chats private store', roomTimestampObject?.length || 0);
                if (roomTimestampObject) {
                  (0, _updatedChatLastTimestamps.updatedChatLastTimestamps)(roomTimestampObject, dispatch);
                }
                if (!hasSyncedHistoryRef.current) {
                  console.log('Updating messages till last');
                  await (0, _updateMessagesTillLast.updateMessagesTillLast)(rooms, newClient);
                  hasSyncedHistoryRef.current = true;
                }
                setClient(newClient);
                setConnectionLost(false);
                console.log('Initialization complete');
              } catch (err) {
                console.warn('privateStore/timestamps failed', err);
                setClient(newClient);
                setConnectionLost(false);
              }
              {
                config?.refreshTokens?.enabled && (0, _apiClient.refresh)();
              }
            } catch (error) {
              console.error(' Error during initialization', error);
              setConnectionLost(true);
              retryTimeout = setTimeout(initXmmpClient, 5000);
            }
          } else {
            if (config?.newArch) {
              if (config?.enableRoomsRetry?.enabled) {
                const isSelectedRoomPresent = (0, _isChatIdPresentInArray.isChatIdPresentInArray)(roomJID, roomsList);
                console.log('Selected room present in existing client?', isSelectedRoomPresent);
                if (!isSelectedRoomPresent) {
                  await getRoomsWithRertyRequest();
                }
              }
            }
            setInited(true);
            console.log(' Getting chats private store for existing client');
            try {
              const roomTimestampObject = await client.getChatsPrivateStoreRequestStanza();
              console.log('Got chats private store for existing client', roomTimestampObject?.length || 0);
              if (roomTimestampObject) {
                (0, _updatedChatLastTimestamps.updatedChatLastTimestamps)(roomTimestampObject, dispatch);
              }
              if (!hasSyncedHistoryRef.current) {
                console.log('Updating messages till last for existing client');
                await (0, _updateMessagesTillLast.updateMessagesTillLast)(rooms, client);
                hasSyncedHistoryRef.current = true;
              }
              setClient(client);
              setConnectionLost(false);
              console.log(' Initialization complete for existing client');
            } catch (err) {
              console.warn('privateStore/timestamps failed (existing client)', err);
              setClient(client);
              setConnectionLost(false);
            }
            {
              config?.refreshTokens?.enabled && (0, _apiClient.refresh)();
            }
          }
        }
        dispatch((0, _roomsSlice.setIsLoading)({
          loading: false
        }));
      } catch (error) {
        console.error(' Fatal error', error);
        setShowModal(false);
        setConnectionLost(true);
        setInited(false);
        dispatch((0, _roomsSlice.setIsLoading)({
          loading: false
        }));
        retryTimeout = setTimeout(initXmmpClient, 5000);
      }
    };
    initXmmpClient();
    return () => {
      clearTimeout(retryTimeout);
    };
  }, [user.xmppPassword, user.xmppUsername]);
  return {
    client,
    inited,
    isRetrying,
    showModal,
    isConnectionLost,
    setClient: setClient,
    setInited,
    setShowModal
  };
};
var _default = exports.default = useChatWrapperInit;
//# sourceMappingURL=useChatWrapperInit.js.map