"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _reactNativeSvg = require("react-native-svg");
var _xml = require("../../../../core/assets/icons/xml");
var _styles = require("./styles");
var _feed = require("../../../../core/legacy/feed");
var _LoadingImage = _interopRequireDefault(require("../LoadingImage"));
var _LoadingVideo = _interopRequireDefault(require("../LoadingVideo"));
var _useAuth = _interopRequireDefault(require("../../../../core/hooks/useAuth"));
var _reactNativePaper = require("react-native-paper");
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _post = require("../../../../core/utils/post");
var _postDetailSlice = _interopRequireDefault(require("../../../../core/stores/slices/postDetailSlice"));
var _globalfeedSlice = _interopRequireDefault(require("../../../../core/stores/slices/globalfeedSlice"));
var _feedSlice = _interopRequireDefault(require("../../../../core/stores/slices/feedSlice"));
var _useMention = _interopRequireDefault(require("../../../hooks/useMention"));
var _reactNativeControlledMentions = require("react-native-controlled-mentions");
var _store = require("../../../../core/stores/store");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const EditPostModal = ({
  visible,
  onClose,
  postDetail,
  onFinishEdit,
  privateCommunityId
}) => {
  var _postDetail$data;
  const theme = (0, _reactNativePaper.useTheme)();
  const styles = (0, _styles.useStyles)();
  const {
    apiRegion
  } = (0, _useAuth.default)();
  const [inputMessage, setInputMessage] = (0, _react.useState)((postDetail === null || postDetail === void 0 || (_postDetail$data = postDetail.data) === null || _postDetail$data === void 0 ? void 0 : _postDetail$data.text) ?? '');
  const [displayImages, setDisplayImages] = (0, _react.useState)([]);
  const [displayVideos, setDisplayVideos] = (0, _react.useState)([]);
  const [mentionPosition, setMentionPosition] = (0, _react.useState)([]);
  const [mentionUsers, setMentionUsers] = (0, _react.useState)([]);
  const [imagePosts, setImagePosts] = (0, _react.useState)([]);
  const [videoPosts, setVideoPosts] = (0, _react.useState)([]);
  const [childrenPostArr, setChildrenPostArr] = (0, _react.useState)([]);
  const {
    updateByPostId: updateByPostIdGlobalFeed
  } = _globalfeedSlice.default.actions;
  const {
    updatePostDetail
  } = _postDetailSlice.default.actions;
  const {
    updateByPostId
  } = _feedSlice.default.actions;
  const dispatch = (0, _store.useUIKitDispatch)();
  const {
    renderInput,
    renderSuggestions
  } = (0, _useMention.default)({
    value: inputMessage,
    onChange: setInputMessage,
    communityId: privateCommunityId,
    setMentionUsers: user => {
      setMentionUsers(prev => [...prev, user]);
    },
    setMentionPosition: position => {
      setMentionPosition(prev => [...prev, position]);
    }
  });
  const parsePostText = (0, _react.useCallback)((text, mentionUsersArr) => {
    const parsedText = text.replace(/@([\w\s-]+)/g, (_, username) => {
      const mentionee = mentionUsersArr.find(user => user.displayName === username);
      const mentioneeId = mentionee ? mentionee.userId : '';
      return `{@}[${username}](${mentioneeId})`;
    });
    return parsedText;
  }, []);
  const getMentionPositions = (0, _react.useCallback)((text, mentioneeIds) => {
    let index = 0;
    let mentions = [];
    let match;
    const mentionRegex = /@([\w-]+)/g;
    while ((match = mentionRegex.exec(text)) !== null) {
      let username = match[1];
      let mentioneeId = mentioneeIds[index++];
      let startIdx = match.index;
      let mention = {
        type: 'user',
        displayName: username,
        index: startIdx,
        length: match[0].length,
        userId: mentioneeId
      };
      mentions.push(mention);
    }
    return mentions;
  }, []);
  const getMentionUsers = (0, _react.useCallback)(async mentionIds => {
    var _postDetail$data2;
    const {
      data
    } = await _tsSdkReactNative.UserRepository.getUserByIds(mentionIds);
    const users = data.map(user => {
      return {
        ...user,
        name: user.displayName,
        id: user.userId
      };
    });
    setMentionUsers(users);
    const parsedText = parsePostText((postDetail === null || postDetail === void 0 || (_postDetail$data2 = postDetail.data) === null || _postDetail$data2 === void 0 ? void 0 : _postDetail$data2.text) ?? '', users);
    setInputMessage(parsedText);
    return users;
  }, []);
  const getPostInfo = (0, _react.useCallback)(async postArray => {
    try {
      const response = await Promise.all(postArray.map(async id => {
        const {
          data: post
        } = await (0, _feed.getPostById)(id);
        return {
          dataType: post.dataType,
          data: post.data
        };
      }));
      response.forEach(item => {
        if ((item === null || item === void 0 ? void 0 : item.dataType) === 'image') {
          setImagePosts(prev => [...prev, `https://api.${apiRegion}.amity.co/api/v3/files/${item === null || item === void 0 ? void 0 : item.data.fileId}/download?size=medium`]);
        } else if ((item === null || item === void 0 ? void 0 : item.dataType) === 'video') {
          setVideoPosts(prev => [...prev, item.data]);
        }
      });
    } catch (error) {
      console.log('error: ', error);
    }
  }, [apiRegion]);
  (0, _react.useEffect)(() => {
    if (childrenPostArr.length > 0) {
      getPostInfo(childrenPostArr);
    }
  }, [childrenPostArr, getPostInfo]);
  (0, _react.useEffect)(() => {
    getPost(postDetail.postId);
  }, [postDetail.postId, visible]);
  (0, _react.useEffect)(() => {
    var _postDetail$mentionee;
    if ((postDetail === null || postDetail === void 0 || (_postDetail$mentionee = postDetail.mentionees) === null || _postDetail$mentionee === void 0 ? void 0 : _postDetail$mentionee.length) > 0) {
      var _postDetail$data3, _postDetail$mentionee2, _postDetail$mentionee3;
      const mentionPositions = getMentionPositions((postDetail === null || postDetail === void 0 || (_postDetail$data3 = postDetail.data) === null || _postDetail$data3 === void 0 ? void 0 : _postDetail$data3.text) ?? '', ((_postDetail$mentionee2 = postDetail.mentionees) === null || _postDetail$mentionee2 === void 0 ? void 0 : _postDetail$mentionee2[0].userIds) ?? []);
      getMentionUsers(((_postDetail$mentionee3 = postDetail.mentionees) === null || _postDetail$mentionee3 === void 0 ? void 0 : _postDetail$mentionee3[0].userIds) ?? []);
      setMentionPosition(mentionPositions);
    } else {
      var _postDetail$data4;
      setInputMessage((postDetail === null || postDetail === void 0 || (_postDetail$data4 = postDetail.data) === null || _postDetail$data4 === void 0 ? void 0 : _postDetail$data4.text) ?? '');
    }
  }, [postDetail]);
  const getPost = postId => {
    const unsubscribePost = _tsSdkReactNative.PostRepository.getPost(postId, async ({
      data
    }) => {
      setChildrenPostArr(data.children);
    });
    unsubscribePost();
  };
  const handleOnClose = () => {
    onClose && onClose();
  };
  const handleEditPost = async () => {
    const mentionees = mentionUsers.map(user => user.id);
    const files = displayImages.length > 0 ? displayImages : (displayVideos === null || displayVideos === void 0 ? void 0 : displayVideos.length) > 0 ? displayVideos : [];
    const fileIds = files ? files.map(item => item.fileId) : [];
    const type = displayImages.length > 0 ? 'image' : displayVideos.length > 0 ? 'video' : 'text';
    if (type === 'text' && (postDetail === null || postDetail === void 0 ? void 0 : postDetail.children.length) > 0) {
      await Promise.allSettled(postDetail === null || postDetail === void 0 ? void 0 : postDetail.children.map(postId => {
        _tsSdkReactNative.PostRepository.deletePost(postId, true);
      }));
    }
    const response = await (0, _feed.editPost)(postDetail.postId, {
      text: (0, _reactNativeControlledMentions.replaceTriggerValues)(inputMessage, ({
        name
      }) => `@${name}`),
      fileIds: fileIds
    }, type, mentionees, mentionPosition);
    if (response) {
      const formattedPost = await (0, _post.amityPostsFormatter)([response]);
      const updatedPost = {
        ...postDetail,
        ...formattedPost[0]
      };
      dispatch(updateByPostId({
        postId: postDetail.postId,
        postDetail: updatedPost
      }));
      dispatch(updateByPostIdGlobalFeed({
        postId: postDetail.postId,
        postDetail: updatedPost
      }));
      dispatch(updatePostDetail(updatedPost));
      onFinishEdit && onFinishEdit({
        text: inputMessage,
        mediaUrls: formattedPost[0].children
      }, type);
      handleOnClose();
    }
  };
  (0, _react.useEffect)(() => {
    if (imagePosts.length > 0) {
      const imagesObject = imagePosts.map(url => {
        const parts = url.split('/');
        const fileId = parts[parts.indexOf('files') + 1];
        return {
          url: url,
          fileName: fileId,
          fileId: fileId,
          isUploaded: true
        };
      });
      setDisplayImages(imagesObject);
    }
  }, [imagePosts]);
  const processVideo = (0, _react.useCallback)(async () => {
    if (videoPosts.length > 0) {
      const videosObject = await Promise.all(videoPosts.map(async item => {
        return {
          url: `https://api.${apiRegion}.amity.co/api/v3/files/${item.videoFileId.original}/download`,
          fileName: item.videoFileId.original,
          fileId: item.videoFileId.original,
          isUploaded: true,
          thumbNail: `https://api.${apiRegion}.amity.co/api/v3/files/${item.thumbnailFileId}/download`
        };
      }));
      setDisplayVideos(videosObject);
    }
  }, [apiRegion, videoPosts]);
  (0, _react.useEffect)(() => {
    processVideo();
  }, [processVideo]);
  const handleOnCloseImage = originalPath => {
    setDisplayImages(prevData => {
      const newData = prevData.filter(item => item.url !== originalPath); // Filter out objects containing the desired value
      return newData; // Remove the element at the specified index
    });
  };
  const handleOnCloseVideo = originalPath => {
    setDisplayVideos(prevData => {
      const newData = prevData.filter(item => item.url !== originalPath); // Filter out objects containing the desired value
      return newData; // Remove the element at the specified index
    });
  };
  return /*#__PURE__*/React.createElement(_reactNative.Modal, {
    visible: visible,
    animationType: "slide"
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.header
  }, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.closeButton,
    onPress: handleOnClose
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.closeIcon)(theme.colors.base),
    width: "17",
    height: "17"
  })), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.headerTextContainer
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.headerText
  }, "Edit Post")), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    onPress: handleEditPost,
    style: styles.headerTextContainer
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.headerText
  }, "Save"))), /*#__PURE__*/React.createElement(_reactNative.KeyboardAvoidingView, {
    behavior: _reactNative.Platform.OS === 'ios' ? 'padding' : 'height',
    keyboardVerticalOffset: _reactNative.Platform.select({
      ios: 100,
      android: 80
    }),
    style: styles.AllInputWrap
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.container
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.AllInputWrap
  }, /*#__PURE__*/React.createElement(_reactNative.ScrollView, {
    style: styles.container,
    keyboardShouldPersistTaps: "handled"
  }, renderInput({
    multiline: true,
    style: styles.textInput,
    placeholder: "What's going on...?",
    placeholderTextColor: theme.colors.baseShade3
  }), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.imageContainer
  }, displayImages.length > 0 && /*#__PURE__*/React.createElement(_reactNative.FlatList, {
    data: displayImages,
    renderItem: ({
      item,
      index
    }) => /*#__PURE__*/React.createElement(_LoadingImage.default, {
      source: item.url,
      onClose: handleOnCloseImage,
      index: index,
      isUploaded: item.isUploaded,
      fileId: item.fileId,
      isEditMode: true
    }),
    extraData: displayImages,
    numColumns: 3
  }), displayVideos.length > 0 && /*#__PURE__*/React.createElement(_reactNative.FlatList, {
    data: displayVideos,
    renderItem: ({
      item,
      index
    }) => /*#__PURE__*/React.createElement(_LoadingVideo.default, {
      source: item.url,
      onClose: handleOnCloseVideo,
      index: index,
      isUploaded: item.isUploaded,
      fileId: item.fileId,
      thumbNail: item.thumbNail,
      isEditMode: true
    }),
    numColumns: 3
  }))))), renderSuggestions({
    type: 'post'
  })));
};
var _default = exports.default = /*#__PURE__*/(0, _react.memo)(EditPostModal);
//# sourceMappingURL=index.js.map