"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _StyledComponents = require("../styled/StyledComponents");
var _reactRedux = require("react-redux");
var _MessageList = _interopRequireDefault(require("./MessageList"));
var _SendInput = _interopRequireDefault(require("../styled/SendInput"));
var _roomsSlice = require("../../roomStore/roomsSlice");
var _Loader = _interopRequireDefault(require("../styled/Loader"));
var _xmppProvider = require("../../context/xmppProvider");
var _ChatHeader = _interopRequireDefault(require("./ChatHeader"));
var _NoMessagesPlaceholder = _interopRequireDefault(require("./NoMessagesPlaceholder"));
var _NewChatModal = _interopRequireDefault(require("../Modals/NewChatModal/NewChatModal"));
var _EditWrapper = require("./EditWrapper");
var _icons = require("../../assets/icons");
var _ChooseChatMessage = require("./ChooseChatMessage");
var _useSendMessage = require("../../hooks/useSendMessage");
var _useRoomInitialization = require("../../hooks/useRoomInitialization");
var _useRoomState = require("../../hooks/useRoomState");
var _useChatSettingState = require("../../hooks/useChatSettingState");
var _CustomTypingIndicator = _interopRequireDefault(require("../styled/StyledInputComponents/CustomTypingIndicator"));
var _reactNative = require("react-native");
var _reactNativeKeyboardController = require("react-native-keyboard-controller");
var _useComposing = _interopRequireDefault(require("../../hooks/useComposing"));
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
/** @format */

// import {PanGestureHandler} from 'react-native-gesture-handler';

const ChatRoom = /*#__PURE__*/_react.default.memo(({
  CustomMessageComponent,
  CustomInputComponent,
  CustomScrollableArea,
  CustomDaySeparator,
  CustomNewMessageLabel,
  handleBackClick,
  eventHandlers: propsEventHandlers
}) => {
  const {
    client
  } = (0, _xmppProvider.useXmppClient)();
  const dispatch = (0, _reactRedux.useDispatch)();
  const [isLoadingMore, setIsLoadingMore] = (0, _react.useState)(false);
  const {
    user,
    config: storeConfig
  } = (0, _useChatSettingState.useChatSettingState)();

  // Merge eventHandlers from props with config (props take precedence)
  // This is necessary because functions can't be stored in Redux
  const configWithEventHandlers = _react.default.useMemo(() => {
    if (propsEventHandlers && storeConfig) {
      return {
        ...storeConfig,
        eventHandlers: propsEventHandlers
      };
    }
    return storeConfig;
  }, [storeConfig, propsEventHandlers]);
  const {
    roomsList,
    activeRoomJID,
    editAction,
    loading,
    globalLoading,
    roomMessages
  } = (0, _useRoomState.useRoomState)();
  const {
    sendMessage: sendMs,
    sendMedia: sendMessageMedia,
    sendEditMessage,
    isLastMessageFromUserAndProcessing
  } = (0, _useSendMessage.useSendMessage)(configWithEventHandlers);
  const {
    sendStartComposing,
    sendEndComposing
  } = (0, _useComposing.default)(configWithEventHandlers || storeConfig);
  const sendMessage = (0, _react.useCallback)(message => {
    if (!activeRoomJID) {
      return;
    }
    dispatch((0, _roomsSlice.setLastViewedTimestamp)({
      chatJID: activeRoomJID,
      timestamp: 0
    }));
    sendMs(message, activeRoomJID);
  }, [activeRoomJID]);
  const sendMedia = (0, _react.useCallback)((data, type) => {
    // Return the promise so callers can sequence the follow-up
    // text send AFTER the upload finishes (consumer expectation:
    // media first, text second — never interleaved).
    return sendMessageMedia(data, type, activeRoomJID || '');
  }, [activeRoomJID]);
  const loadMoreMessages = (0, _react.useCallback)(async (chatJID, max, idOfMessageBefore) => {
    if (isLoadingMore || roomsList?.[chatJID]?.historyComplete) {
      return;
    }
    const lastMsgId = typeof idOfMessageBefore !== 'string' ? idOfMessageBefore : Number(roomsList[chatJID].messages[roomsList[chatJID].messages.length - 2]?.id);
    setIsLoadingMore(true);
    try {
      // Return the promise so MessageList's `await loadMoreMessages`
      // actually waits for MAM to respond before its own onEndReached
      // re-arms — otherwise the awaited call resolves with `undefined`
      // immediately and rapid scrolls fire repeat requests that step
      // on each other.
      await client?.getHistoryStanza(chatJID, max, lastMsgId);
    } finally {
      setIsLoadingMore(false);
    }
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [client?.client?.jid, isLoadingMore, roomsList]);
  const onCloseEdit = () => {
    dispatch((0, _roomsSlice.setEditAction)({
      isEdit: false
    }));
  };
  (0, _react.useEffect)(() => {
    if (!activeRoomJID) {
      return;
    }
    dispatch((0, _roomsSlice.setLastViewedTimestamp)({
      chatJID: activeRoomJID,
      timestamp: 0
    }));
    setIsLoadingMore(false);
    return () => {
      if (client) {
        client.actionSetTimestampToPrivateStoreStanza(activeRoomJID, new Date().getTime(), Object.keys(roomsList));
      }
      dispatch((0, _roomsSlice.setLastViewedTimestamp)({
        chatJID: activeRoomJID,
        timestamp: new Date().getTime()
      }));
      dispatch((0, _roomsSlice.deleteRoomMessage)({
        roomJID: activeRoomJID,
        messageId: 'delimiter-new'
      }));
      setIsLoadingMore(false);
    };
  }, [activeRoomJID]);

  // hooks useEffects
  // useRoomUrl(activeRoomJID || "", roomsList, config);

  (0, _useRoomInitialization.useRoomInitialization)(activeRoomJID || '', roomsList, configWithEventHandlers || storeConfig || {}, roomMessages.length);
  if (Object.keys(roomsList)?.length < 1 && !loading && !globalLoading) {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_StyledComponents.NonRoomChat, {
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_NewChatModal.default, {})
    });
  }
  if (!activeRoomJID || !roomsList?.[activeRoomJID]) {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_ChooseChatMessage.ChooseChatMessage, {});
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNativeKeyboardController.KeyboardAvoidingView, {
    style: {
      flex: 1
    },
    behavior: _reactNative.Platform.OS === 'ios' ? 'padding' : 'height',
    keyboardVerticalOffset: configWithEventHandlers?.keyboardVerticalOffset ?? 0,
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_StyledComponents.ChatContainer, {
      style: configWithEventHandlers?.chatRoomStyles ? configWithEventHandlers.chatRoomStyles : undefined,
      children: [!configWithEventHandlers?.disableHeader && /*#__PURE__*/(0, _jsxRuntime.jsx)(_ChatHeader.default, {
        currentRoom: roomsList[activeRoomJID],
        handleBackClick: handleBackClick
      }), configWithEventHandlers?.chatHeaderAdditional?.enabled && configWithEventHandlers.chatHeaderAdditional.element(), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
        style: {
          flex: 1
        },
        children: loading || globalLoading ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
          style: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center'
          },
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Loader.default, {
            color: configWithEventHandlers?.colors?.primary
          })
        }) : Object.keys(roomsList).length < 1 || !activeRoomJID ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
          style: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center'
          },
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.NoSelectedChatIcon, {})
        }) : !roomMessages || roomMessages.length === 0 ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
          style: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#ffffff'
          },
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_NoMessagesPlaceholder.default, {})
        }) : CustomScrollableArea ? /*#__PURE__*/(0, _jsxRuntime.jsx)(CustomScrollableArea, {
          roomJID: activeRoomJID,
          messages: roomMessages,
          decoratedMessages: roomMessages.map((msg, idx) => ({
            message: msg,
            showDateLabel: idx === 0 || new Date(msg.date).toDateString() !== new Date(roomMessages[idx - 1]?.date).toDateString()
          })),
          isLoading: isLoadingMore,
          isReply: false,
          loadMoreMessages: loadMoreMessages,
          renderMessage: decorated => CustomMessageComponent ? /*#__PURE__*/(0, _jsxRuntime.jsx)(CustomMessageComponent, {
            message: decorated.message,
            isUser: decorated.message.user.id === user.xmppUsername,
            isReply: false
          }) : null,
          scrollController: {
            scrollToBottom: () => {},
            waitForImagesLoaded: async () => {},
            showScrollButton: false,
            newMessagesCount: 0,
            resetNewMessageCounter: () => {}
          },
          typingIndicator: roomsList[activeRoomJID]?.composing ? configWithEventHandlers?.customTypingIndicator?.customComponent ? /*#__PURE__*/(0, _jsxRuntime.jsx)(configWithEventHandlers.customTypingIndicator.customComponent, {
            usersTyping: roomsList[activeRoomJID]?.composingList || [],
            text: typeof configWithEventHandlers.customTypingIndicator.text === 'function' ? configWithEventHandlers.customTypingIndicator.text(roomsList[activeRoomJID]?.composingList || []) : configWithEventHandlers.customTypingIndicator.text || 'Typing...',
            isVisible: true
          }) : null : undefined,
          config: configWithEventHandlers
        }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_MessageList.default, {
          loadMoreMessages: loadMoreMessages,
          CustomMessage: CustomMessageComponent,
          CustomDaySeparator: CustomDaySeparator,
          CustomNewMessageLabel: CustomNewMessageLabel,
          user: user,
          roomJID: activeRoomJID,
          config: configWithEventHandlers,
          loading: isLoadingMore,
          isReply: false
        })
      }), editAction && editAction.isEdit && /*#__PURE__*/(0, _jsxRuntime.jsx)(_EditWrapper.EditWrapper, {
        text: editAction.text || '',
        onClose: onCloseEdit
      }), CustomInputComponent ? /*#__PURE__*/(0, _jsxRuntime.jsx)(CustomInputComponent, {
        sendMessage: editAction && editAction.isEdit ? sendEditMessage : sendMessage,
        sendMedia: sendMedia,
        config: configWithEventHandlers,
        isLoading: loading,
        onFocus: sendStartComposing,
        onBlur: sendEndComposing,
        isMessageProcessing: isLastMessageFromUserAndProcessing(activeRoomJID),
        editMessage: editAction && editAction.text
      }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_SendInput.default, {
        editMessage: editAction && editAction.text,
        sendMessage: editAction && editAction.isEdit ? sendEditMessage : sendMessage,
        sendMedia: sendMedia,
        config: configWithEventHandlers,
        isLoading: loading,
        onFocus: sendStartComposing,
        onBlur: sendEndComposing,
        isMessageProcessing: isLastMessageFromUserAndProcessing(activeRoomJID)
      }), configWithEventHandlers?.customTypingIndicator?.enabled && (configWithEventHandlers.customTypingIndicator.position === 'overlay' || configWithEventHandlers.customTypingIndicator.position === 'floating') && roomsList[activeRoomJID]?.composing && /*#__PURE__*/(0, _jsxRuntime.jsx)(_CustomTypingIndicator.default, {
        usersTyping: roomsList[activeRoomJID]?.composingList || ['User'],
        text: configWithEventHandlers.customTypingIndicator.text,
        position: configWithEventHandlers.customTypingIndicator.position,
        styles: configWithEventHandlers.customTypingIndicator.styles,
        customComponent: configWithEventHandlers.customTypingIndicator.customComponent,
        isVisible: roomsList[activeRoomJID]?.composing || false
      })]
    })
  });
});
var _default = exports.default = ChatRoom;
//# sourceMappingURL=ChatRoom.js.map