import {
  MediaUploadErrorKey
} from "./../ricos-content/index.js";
import { getHighestQualityVideo } from "./get-highest-quality-video.js";
import { getMediaFileType } from "./get-media-file-type.js";
import { getUploadError } from "./get-upload-error.js";
import { MediaType } from "./request-service-provider/consts.js";
import { createUploadFn } from "./request-service-provider/media-manager-uploader.js";
import { withFileSizeLimitation } from "./with-file-size-limitation.js";
const createMediaUploadFn = (services) => {
  const { metaSiteId, uid, siteOwnerId } = services.wixInstance();
  if (!metaSiteId) {
    return void 0;
  }
  const upload = createUploadFn(services);
  const handleUploadError = (error, updateEntity) => {
    const isOwner = siteOwnerId === uid;
    const mediaUploadError = getUploadError(error, metaSiteId, isOwner);
    updateEntity({ error: mediaUploadError });
  };
  const imageUpload = (file, updateEntity) => {
    return upload(file, MediaType.IMAGE).then(({ file_name, original_file_name, height, width }) => {
      updateEntity({
        data: {
          id: file_name,
          height,
          width,
          original_file_name,
          file_name
        }
      });
    }).catch((error) => {
      return handleUploadError(error, updateEntity);
    });
  };
  const videoUpload = (file, updateEntity) => {
    return upload(file, MediaType.VIDEO).then(({ file_output: { video, image } }) => {
      updateEntity({
        data: {
          pathname: getHighestQualityVideo(video).url,
          thumbnail: {
            pathname: image[0].url,
            width: image[0].width,
            height: image[0].height
          },
          title: file.name
        }
      });
    }).catch((error) => handleUploadError(error, updateEntity));
  };
  const getUnsupportedExtensionError = (fileName) => {
    return {
      key: MediaUploadErrorKey.UNSUPPORTED_EXTENSION,
      args: { extension: fileName.split(".").pop()?.toLowerCase() || "" }
    };
  };
  const galleryUpload = (file, updateEntity) => {
    const fileType = getMediaFileType(file.name);
    if (fileType === MediaType.IMAGE) {
      return imageUpload(file, updateEntity);
    } else if (fileType === MediaType.VIDEO) {
      return videoUpload(file, updateEntity);
    } else {
      return updateEntity({
        error: getUnsupportedExtensionError(file.name)
      });
    }
  };
  return withFileSizeLimitation(galleryUpload, services.editorProps.fileUploadSizeLimit);
};
export {
  createMediaUploadFn
};
//# sourceMappingURL=create-media-upload-fn.js.map
