"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.FullScreenVideo = void 0;
var _react = _interopRequireWildcard(require("react"));
var _native = _interopRequireDefault(require("styled-components/native"));
var _styledModalComponents = require("../styledModalComponents");
var _icons = require("../../../assets/icons");
var _ModalHeaderComponent = _interopRequireDefault(require("../ModalHeaderComponent"));
var _reactRedux = require("react-redux");
var _Button = _interopRequireDefault(require("../../styled/Button"));
var _MediaComponents = require("../../styled/StyledInputComponents/MediaComponents");
var _chatSettingsSlice = require("../../../roomStore/chatSettingsSlice");
var _reactNative = require("react-native");
var _expoAv = require("expo-av");
var FileSystem = _interopRequireWildcard(require("expo-file-system/legacy"));
var MediaLibrary = _interopRequireWildcard(require("expo-media-library"));
var _ToastContext = require("../../../context/ToastContext");
var _PdfView = _interopRequireDefault(require("./PdfView"));
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); }
const FullScreenVideo = exports.FullScreenVideo = _native.default.View`
  width: 100%;
  height: 100%;
  object-fit: contain;
`;
const FilePreviewModal = ({
  handleCloseModal
}) => {
  const dispatch = (0, _reactRedux.useDispatch)();
  const {
    showToast
  } = (0, _ToastContext.useToast)();
  const {
    activeFile
  } = (0, _reactRedux.useSelector)(state => state.chatSettingStore);
  if (!activeFile) {
    return;
  }
  const requestStoragePermission = async () => {
    try {
      const {
        status
      } = await MediaLibrary.requestPermissionsAsync();
      return status === 'granted';
    } catch (error) {
      console.error('Error requesting permission:', error);
      return false;
    }
  };
  const saveToGallery = async () => {
    const hasPermission = await requestStoragePermission();
    if (!hasPermission) {
      _reactNative.Alert.alert('Permission Denied', 'Storage permission is required to save files to the gallery.');
      return;
    }
    try {
      let fileName = activeFile.fileName || `media_${Date.now()}`;
      if (!fileName.includes('.')) {
        fileName += activeFile.mimetype.startsWith('image/') ? '.jpg' : '.mp4';
      }
      const filePath = FileSystem.cacheDirectory + fileName;
      const download = await FileSystem.downloadAsync(activeFile.fileURL, filePath);
      if (download.status === 200) {
        await MediaLibrary.saveToLibraryAsync(download.uri);
        showToast({
          id: Date.now().toString(),
          title: 'Success',
          message: 'Save successful',
          type: 'success'
        });
      } else {
        _reactNative.Alert.alert('Error', 'Failed to save the file.');
      }
    } catch (err) {
      _reactNative.Alert.alert('Error', `Failed to save the file: ${activeFile.fileName}`);
    }
  };
  const saveFileToDownloads = async () => {
    try {
      const fileName = activeFile.fileName || `file_${Date.now()}`;
      const filePath = FileSystem.cacheDirectory + fileName;
      const download = await FileSystem.downloadAsync(activeFile.fileURL, filePath);
      if (download.status === 200) {
        if (_reactNative.Platform.OS === 'android') {
          const hasPermission = await requestStoragePermission();
          if (hasPermission) {
            await MediaLibrary.createAssetAsync(download.uri);
          }
        }
        showToast({
          id: Date.now().toString(),
          title: 'Success',
          message: 'Save successful',
          type: 'success'
        });
      } else {
        _reactNative.Alert.alert('Error', 'Failed to save the file.');
      }
    } catch (err) {
      console.error('Error saving file:', err);
      _reactNative.Alert.alert('Error', 'Failed to save the file.');
    }
  };
  const saveClick = async () => {
    if (activeFile.mimetype.startsWith('image/') || activeFile.mimetype.startsWith('video/')) {
      await saveToGallery();
    } else {
      await saveFileToDownloads();
    }
  };
  const closeModal = () => {
    dispatch((0, _chatSettingsSlice.setActiveFile)({
      fileName: '',
      fileURL: '',
      mimetype: ''
    }));
    handleCloseModal?.();
  };
  const getMediaComponent = (0, _react.useMemo)(() => {
    switch (true) {
      case activeFile.mimetype.startsWith('image/'):
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_MediaComponents.FullScreenImage, {
          src: activeFile.fileURL || 'https://as2.ftcdn.net/v2/jpg/02/51/95/53/1000_F_251955356_FAQH0U1y1TZw3ZcdPGybwUkH90a3VAhb.jpg',
          alt: activeFile.fileName
        });
      case activeFile.mimetype.startsWith('video/'):
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_expoAv.Video, {
          style: {
            width: '100%',
            height: '100%'
          },
          source: {
            uri: activeFile.fileURL
          },
          useNativeControls: true,
          resizeMode: _expoAv.ResizeMode.CONTAIN,
          shouldPlay: false
        });
      case activeFile.mimetype === 'application/pdf':
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_PdfView.default, {
          pdfUrl: activeFile.fileURL
        });
      default:
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
          style: {
            backgroundColor: '#FFF8ED',
            borderRadius: 16,
            display: 'flex',
            padding: 16
          },
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
            children: "Unable to open the uploaded document. The file format is not supported by the system. Please upload a file in a compatible format. You still can download this file."
          })
        });
    }
  }, [activeFile]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.ModalContainerFullScreen, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_ModalHeaderComponent.default, {
      handleCloseModal: closeModal,
      headerTitle: 'File preview',
      rightMenu: /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
          onPress: saveClick,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.SaveIcon, {})
        })
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.CenterContainer, {
      style: {
        display: 'flex',
        height: '100%',
        justifyContent: 'center',
        overflow: 'hidden',
        padding: 16
      },
      children: getMediaComponent
    })]
  });
};
var _default = exports.default = FilePreviewModal;
//# sourceMappingURL=FilePreviewModal.js.map