"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var handle_gallery_upload_exports = {};
__export(handle_gallery_upload_exports, {
  getGalleryPickMedia: () => getGalleryPickMedia,
  handleGalleryUpload: () => handleGalleryUpload
});
module.exports = __toCommonJS(handle_gallery_upload_exports);
var import_next_schema = require("./../ricos-schema/next-schema/index.js");
var import_create_media_upload_fn = require("./../_shared/create-media-upload-fn.js");
var import_get_highest_quality_video = require("./../_shared/get-highest-quality-video.js");
var import_log_invariant = require("./../_shared/log-invariant.js");
var import_create_open_media_manager_fn = require("./../_shared/media-manager/create-open-media-manager-fn.js");
var import_types = require("./../_shared/media-manager/types.js");
var import_uncreachable = require("./../_shared/uncreachable.js");
var import_upload = require("./../_shared/upload/upload.js");
var import_layout_data_provider = require(".//layout-data-provider.js");
var import_consts = require("./consts.js");
var import_types2 = require("./types.js");
const getGalleryAttributes = ({
  uploadedData,
  componentData,
  fileState
}) => {
  const fileType = uploadedData.thumbnail ? "video" : "image";
  let galleryItem;
  if (fileType === "video") {
    galleryItem = galleryVideoBuilder(uploadedData);
  } else {
    galleryItem = galleryImageBuilder(uploadedData);
  }
  const itemPos = fileState?.itemIndex;
  const newComponentData = setItemInGallery(galleryItem, componentData, itemPos);
  return {
    ...newComponentData,
    error: null
  };
};
const getGalleryErrorAttributes = (error, componentData, fileState) => {
  const itemPos = fileState ? fileState.itemIndex : void 0;
  const galleryItem = {
    error,
    ...itemPos !== void 0 ? componentData.items?.[itemPos] ?? {} : {}
  };
  const newComponentData = setItemInGallery(galleryItem, componentData, itemPos);
  return {
    ...newComponentData
  };
};
const setItemInGallery = (item, componentData, itemPos) => {
  let { items } = componentData;
  if (typeof itemPos === "undefined") {
    items = [...items ?? [], item];
  } else {
    items = items ? [...items] : [];
    items[itemPos] = item;
  }
  return { ...componentData, items };
};
const isPickMediaImageType = (data) => "type" in data && data.type === "image";
const galleryImageBuilder = (img) => {
  if (isPickMediaImageType(img)) {
    return {
      image: {
        media: {
          src: img.src,
          height: img.height,
          width: img.width
        }
      },
      loading: false
    };
  }
  return {
    image: {
      media: {
        src: { url: img.file_name },
        height: img.height,
        width: img.width
      }
    },
    loading: false
  };
};
const isPickMediaVideoType = (data) => "type" in data && data.type === "video";
const galleryVideoBuilder = (video) => {
  if (isPickMediaVideoType(video)) {
    return {
      video: {
        media: {
          src: video.src,
          height: video.height,
          width: video.width
        },
        thumbnail: {
          src: video.thumbnail.src,
          width: video.thumbnail.width,
          height: video.thumbnail.height
        }
      },
      loading: false
    };
  }
  const {
    thumbnail: { pathname: url, width, height }
  } = video;
  return {
    video: {
      media: {
        src: { url: video.pathname },
        height: video.height || height,
        width: video.width || width
      },
      thumbnail: {
        src: { url },
        width,
        height
      }
    },
    loading: false
  };
};
const getGalleryFileType = (type) => {
  return type.match("image/*") ? "image" : type.match("video/*") ? "video" : "";
};
const createMediaFileSelectionFn = (services) => {
  const openMediaManager = (0, import_create_open_media_manager_fn.createOpenMediaManagerFn)();
  if (!openMediaManager) {
    return void 0;
  }
  return (updateEntity, options, onCancel) => openMediaManager({
    mediaType: import_types.MediaManagerMediaType.ALL_MEDIA,
    appDefId: services.wixInstance().appDefId,
    isMultiSelect: options.multiple
  }).then((items) => {
    const mediaData = items.reduce(
      (acc, media) => {
        switch (media.mediaType) {
          case "video": {
            const { title, height, width } = media;
            const thumbnail = media.fileOutput?.image[0];
            const { url: pathname } = (0, import_get_highest_quality_video.getHighestQualityVideo)(media.fileOutput.video);
            return [
              ...acc,
              {
                pathname,
                height,
                width,
                title,
                thumbnail: {
                  pathname: thumbnail.url,
                  height: thumbnail.height,
                  width: thumbnail.width
                }
              }
            ];
          }
          case "picture": {
            const { id, fileName, title, height, width } = media;
            return [
              ...acc,
              {
                id,
                height,
                width,
                original_file_name: title,
                file_name: fileName
              }
            ];
          }
          default:
            return acc;
        }
      },
      []
    );
    updateEntity({
      data: mediaData,
      // @ts-expect-error
      index: options.index
    });
  }).catch(onCancel);
};
const getGalleryPickMedia = ({
  services,
  handleFileUpload
}) => {
  const devPickMedia = services.devService().pickMedia;
  const editorPickMedia = services.editorProps.pickMedia?.pickGallery;
  const handleFileSelection = services.devService().handleFileSelection ?? createMediaFileSelectionFn(services);
  return devPickMedia ? devPickMedia : editorPickMedia ? editorPickMedia : handleFileSelection ? async ({ multiple }) => {
    try {
      const data = await new Promise(
        (resolve, reject) => handleFileSelection(
          ({ data: data2 }) => resolve(data2),
          { multiple, index: void 0 },
          reject
        )
      );
      return { type: "ready-media", media: data instanceof Array ? data : [data] };
    } catch {
      return { type: "cancel" };
    }
  } : async ({ mimeType, multiple }) => {
    const files = await services.uploadService?.selectFiles({ accept: mimeType, multiple }) ?? [];
    return { type: "file", file: files, customUploadFn: handleFileUpload };
  };
};
const DEFAULT_DATA = {
  items: [],
  options: import_layout_data_provider.layoutRicosData[import_next_schema.GalleryOptions_Layout_Type.GRID]
};
const handleGalleryUpload = async ({
  publicCommands,
  services,
  config,
  nodeId,
  fileState,
  referenceElement
}) => {
  const { accept = import_consts.fileInputAccept, multi = true } = config ?? {};
  const multiple = fileState ? false : multi;
  const handleFileUpload = services.devService().handleFileUpload ?? (0, import_create_media_upload_fn.createMediaUploadFn)(services);
  const pickMedia = getGalleryPickMedia({ services, handleFileUpload });
  const result = await pickMedia({ mimeType: accept, multiple });
  switch (result.type) {
    case "ready-media": {
      if (!nodeId) {
        const componentData = result.media.reduce(
          (acc, item, index) => {
            return getGalleryAttributes({
              uploadedData: item,
              componentData: acc,
              fileState: { itemIndex: index }
            });
          },
          { ...DEFAULT_DATA }
        );
        publicCommands.insertBlockWithBlankLines(import_types2.GALLERY_TYPE, componentData, {
          updateSelection: true
        });
        return;
      }
      const rootItemsLength = publicCommands?.getBlockComponentData(nodeId)?.items?.length || 0;
      result.media.forEach((item, index) => {
        setTimeout(() => {
          const componentData = publicCommands?.getBlockComponentData(
            nodeId
          );
          publicCommands.setBlock(
            nodeId,
            import_types2.GALLERY_TYPE,
            getGalleryAttributes({
              uploadedData: item,
              componentData,
              fileState: fileState ? fileState : { itemIndex: rootItemsLength + index }
            })
          );
        });
      });
      return;
    }
    case "file": {
      const files = result.file;
      const targetNodeId = nodeId ?? publicCommands.insertBlockWithBlankLines(import_types2.GALLERY_TYPE, DEFAULT_DATA, {
        updateSelection: true
      });
      const rootItemsLength = publicCommands?.getBlockComponentData(targetNodeId)?.items?.length || 0;
      await Promise.all(
        files.map(async (_file, index) => {
          const file = new File([_file], _file.name, { type: _file.type });
          const trackBi = services.uploadService.trackUploadBi(import_types2.GALLERY_TYPE, file.size, file.name);
          const itemIndex = fileState ? fileState.itemIndex : rootItemsLength + index;
          try {
            const componentData2 = publicCommands?.getBlockComponentData(targetNodeId);
            const fileType = getGalleryFileType(file.type);
            const galleryItem = { [fileType]: { media: { src: { url: "" } } }, loading: true };
            const newComponentData = setItemInGallery(galleryItem, componentData2, itemIndex);
            publicCommands?.setBlock(targetNodeId, import_types2.GALLERY_TYPE, {
              ...newComponentData,
              loading: true,
              error: null
            });
            trackBi?.start();
            const uploadFn = result.customUploadFn || handleFileUpload;
            if (!uploadFn) {
              (0, import_log_invariant.logInvariant)(Error("No upload function provided"));
              throw new Error("No upload function provided");
            }
            const uploadedFile = await (0, import_upload.upload)(uploadFn, file);
            publicCommands?.setBlock(targetNodeId, import_types2.GALLERY_TYPE, {
              ...getGalleryAttributes({
                uploadedData: uploadedFile.data,
                componentData: publicCommands?.getBlockComponentData(
                  targetNodeId
                ),
                fileState: { itemIndex }
              })
            });
            trackBi?.success();
          } catch (error) {
            const componentData2 = publicCommands?.getBlockComponentData(targetNodeId);
            publicCommands?.setBlock(
              targetNodeId,
              import_types2.GALLERY_TYPE,
              getGalleryErrorAttributes(error, componentData2, { itemIndex })
            );
            trackBi?.error(error);
            services.uploadService.notifyError(error);
          }
        })
      );
      const componentData = publicCommands?.getBlockComponentData(targetNodeId);
      publicCommands?.setBlock(targetNodeId, import_types2.GALLERY_TYPE, {
        ...componentData,
        loading: false
      });
      return;
    }
    case "cancel": {
      services.modals.notifyExternalModalClosed({ focusReturnElement: referenceElement });
      return;
    }
    default: {
      console.error((0, import_uncreachable.unreachable)(result));
      return;
    }
  }
};
//# sourceMappingURL=handle-gallery-upload.js.map
