"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_video_upload_exports = {};
__export(handle_video_upload_exports, {
  handleVideoUpload: () => handleVideoUpload
});
module.exports = __toCommonJS(handle_video_upload_exports);
var import_ricos_content = require("./../ricos-content/index.js");
var import_get_highest_quality_video = require("./../_shared/get-highest-quality-video.js");
var import_get_upload_error = require("./../_shared/get-upload-error.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_consts = require("./../_shared/request-service-provider/consts.js");
var import_media_manager_uploader = require("./../_shared/request-service-provider/media-manager-uploader.js");
var import_uncreachable = require("./../_shared/uncreachable.js");
var import_upload = require("./../_shared/upload/upload.js");
var import_with_file_size_limitation = require("./../_shared/with-file-size-limitation.js");
var import_constants = require("./constants.js");
const isPickMediaType = (data) => "type" in data && data.type === "video";
const getVideoAttributes = ({
  uploadData,
  componentData,
  config
}) => {
  const disableDownload = componentData?.video?.src ? componentData.disableDownload : config.disableDownloadDefault || null;
  if (isPickMediaType(uploadData)) {
    return {
      video: { src: uploadData.src },
      ...uploadData.thumbnail ? {
        thumbnail: uploadData.thumbnail
      } : {},
      ...uploadData.title ? { title: uploadData.title } : {},
      disableDownload
    };
  }
  const { pathname, thumbnail: uploadedThumbnail, url: uploadedUrl, title } = uploadData;
  const src = pathname ? { id: pathname } : { url: uploadedUrl };
  const thumbnailObject = uploadedThumbnail ? {
    thumbnail: {
      src: { id: uploadedThumbnail.pathname },
      width: uploadedThumbnail.width,
      height: uploadedThumbnail.height
    }
  } : {};
  const titleObject = title ? { title } : {};
  return {
    video: { src },
    ...thumbnailObject,
    ...titleObject,
    disableDownload
  };
};
const getVideoPickMedia = ({
  services,
  handleFileUpload
}) => {
  const editorPickMedia = services.editorProps.pickMedia?.pickVideo;
  const devPickMedia = services.devService().pickMedia;
  const handleFileSelection = services.devService().handleFileSelection ?? createHandleFileSelectionFn(services);
  return devPickMedia ? devPickMedia : editorPickMedia ? editorPickMedia : handleFileSelection ? async () => {
    try {
      const data = await new Promise(
        (resolve, reject) => handleFileSelection(({ data: data2 }) => resolve(data2), reject)
      );
      return { type: "ready-media", media: [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 handleVideoUpload = async ({
  services,
  config,
  publicCommands,
  nodeId
}) => {
  const handleFileUpload = createHandleFileUploadFn(services);
  const pickMedia = getVideoPickMedia({ services, handleFileUpload });
  const result = await pickMedia({ mimeType: "video/*", multiple: false }).catch(() => ({
    type: "cancel"
  }));
  const clearUploadToken = (targetNodeId) => {
    publicCommands?.setBlock(targetNodeId, import_ricos_content.VIDEO_TYPE, {
      ...publicCommands?.getBlockComponentData(targetNodeId),
      uploadToken: null
    });
  };
  const getUploadToken = (targetNodeId) => {
    return publicCommands?.getBlockComponentData(targetNodeId)?.uploadToken;
  };
  switch (result.type) {
    case "ready-media": {
      const data = result.media[0] || {};
      if (nodeId) {
        const componentData = publicCommands?.getBlockComponentData(nodeId);
        publicCommands?.setBlock(nodeId, import_ricos_content.VIDEO_TYPE, {
          ...componentData,
          ...getVideoAttributes({ uploadData: data, componentData, config })
        });
        return;
      }
      queueMicrotask(() => {
        publicCommands.insertBlockWithBlankLines(
          import_ricos_content.VIDEO_TYPE,
          {
            ...getVideoAttributes({
              uploadData: data,
              componentData: null,
              config
            }),
            ...import_constants.RICOS_DEFAULTS
          },
          {
            updateSelection: true
          }
        );
      });
      return;
    }
    case "file": {
      const files = result.file;
      const targetNodeId = nodeId || publicCommands.insertBlockWithBlankLines(
        import_ricos_content.VIDEO_TYPE,
        {
          ...import_constants.RICOS_DEFAULTS,
          loading: true
        },
        {
          updateSelection: true
        }
      );
      const uploadToken = Symbol("upload-token");
      const file = Array.isArray(files) ? files[0] : files;
      const trackBi = services.uploadService.trackUploadBi(import_ricos_content.VIDEO_TYPE, file.size, file.name);
      try {
        const url = URL.createObjectURL(file);
        await Promise.resolve();
        publicCommands?.setBlock(targetNodeId, import_ricos_content.VIDEO_TYPE, {
          ...publicCommands?.getBlockComponentData(targetNodeId),
          video: {
            src: { url }
          },
          disableDownload: config.disableDownloadDefault,
          loading: true,
          error: null,
          uploadToken
        });
        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);
        if (getUploadToken(targetNodeId) !== uploadToken) {
          URL.revokeObjectURL(url);
          return;
        }
        const uploadData = uploadedFile.data || {};
        const componentData = publicCommands?.getBlockComponentData(targetNodeId);
        publicCommands?.setBlock(targetNodeId, import_ricos_content.VIDEO_TYPE, {
          ...componentData,
          ...getVideoAttributes({ uploadData, componentData, config }),
          tempData: null,
          loading: null,
          error: null
        });
        URL.revokeObjectURL(url);
        trackBi?.success();
      } catch (error) {
        if (getUploadToken(targetNodeId) === uploadToken) {
          const componentData = publicCommands?.getBlockComponentData(targetNodeId);
          publicCommands?.setBlock(targetNodeId, import_ricos_content.VIDEO_TYPE, {
            ...componentData,
            error,
            loading: null
          });
          trackBi?.error(error);
          services.uploadService.notifyError(error);
        }
      } finally {
        if (getUploadToken(targetNodeId) === uploadToken) {
          clearUploadToken(targetNodeId);
        }
      }
      return;
    }
    case "cancel": {
      services.modals.notifyExternalModalClosed();
      return;
    }
    default: {
      console.error((0, import_uncreachable.unreachable)(result));
      return;
    }
  }
};
const createHandleFileUploadFn = (services) => {
  const { metaSiteId, uid, siteOwnerId } = services.wixInstance();
  if (!metaSiteId) {
    return void 0;
  }
  const videoUpload = (file, updateEntity) => {
    const upload2 = (0, import_media_manager_uploader.createUploadFn)(services);
    return upload2(file, import_consts.MediaType.VIDEO).then(({ file_output: { video, image } }) => {
      updateEntity({
        data: {
          pathname: (0, import_get_highest_quality_video.getHighestQualityVideo)(video).url,
          thumbnail: {
            pathname: image[0].url,
            width: image[0].width,
            height: image[0].height
          },
          title: file.name
        }
      });
    }).catch((error) => {
      const isOwner = siteOwnerId === uid;
      const mediaUploadError = (0, import_get_upload_error.getUploadError)(error, metaSiteId, isOwner);
      updateEntity({ error: mediaUploadError });
    });
  };
  return (0, import_with_file_size_limitation.withFileSizeLimitation)(videoUpload, services.editorProps.fileUploadSizeLimit);
};
const createHandleFileSelectionFn = (services) => {
  const openMediaManager = (0, import_create_open_media_manager_fn.createOpenMediaManagerFn)();
  if (!openMediaManager) {
    return void 0;
  }
  return (updateEntity, onCancel) => openMediaManager({
    mediaType: import_types.MediaManagerMediaType.VIDEO,
    appDefId: services.wixInstance().appDefId
  }).then((items) => {
    const { fullTitle, title, fileOutput } = items[0];
    const { video, image } = fileOutput;
    const { url: pathname } = (0, import_get_highest_quality_video.getHighestQualityVideo)(video);
    const { url, width, height } = image[0];
    const thumbnail = { pathname: url, width, height };
    const videoTitle = fullTitle ?? title;
    const titleObject = videoTitle ? { title: videoTitle } : {};
    updateEntity({ data: { pathname, thumbnail, ...titleObject } });
  }).catch(onCancel);
};
//# sourceMappingURL=handle-video-upload.js.map
