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);

// src/components/dataSourceComponents/fields/Upload/utils.tsx
var utils_exports = {};
__export(utils_exports, {
  checkFileCount: () => checkFileCount,
  createMultilingualData: () => createMultilingualData,
  createMultilingualFileList: () => createMultilingualFileList,
  genFileListByString: () => genFileListByString,
  generateUid: () => generateUid,
  getDefaultFileList: () => getDefaultFileList,
  getFileMetadataParams: () => getFileMetadataParams,
  getFileName: () => getFileName,
  getFileType: () => getFileType,
  getMediaMetadata: () => getMediaMetadata,
  getPointSuffix: () => getPointSuffix,
  getSuffix: () => getSuffix,
  isValueEqual: () => isValueEqual
});
module.exports = __toCommonJS(utils_exports);
var import_utils = require("@pisell/utils");
var import_locales = require("../../../../locales");
var import_constants = require("./constants");
var generateUid = () => {
  return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
};
var getSuffix = (name) => name.split(".").pop() || "";
var getPointSuffix = (name) => `.${getSuffix(name)}`;
var getFileType = (name) => getPointSuffix(getSuffix(name));
var getFileName = (url) => {
  const parts = url.split("/");
  return parts[parts.length - 1] || "";
};
var checkFileCount = ({
  multiple,
  minCount,
  maxCount,
  valueLength
}) => {
  if (!multiple)
    return { success: true };
  if (minCount === maxCount && valueLength !== minCount) {
    return {
      success: false,
      message: (0, import_locales.getText)("pisell-upload-count-error")(minCount)
    };
  }
  if (minCount !== maxCount && (valueLength < minCount || valueLength > maxCount)) {
    return {
      success: false,
      message: (0, import_locales.getText)("pisell-upload-count-error")(`${minCount}-${maxCount}`)
    };
  }
  return { success: true };
};
var createVideoMetadata = async (file) => {
  return new Promise((resolve) => {
    const video = document.createElement("video");
    const canvas = document.createElement("canvas");
    video.preload = "metadata";
    let hasMetadata = false;
    let hasSeeked = false;
    const tryResolve = () => {
      if (!hasMetadata || !hasSeeked)
        return;
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext("2d");
      ctx == null ? void 0 : ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      canvas.toBlob(
        (blob) => {
          const metadata = {
            width: video.videoWidth,
            height: video.videoHeight,
            duration: video.duration,
            bitrate: file.size / video.duration
          };
          if (blob) {
            metadata.cover = new File([blob], `${file.name}-cover.jpg`, {
              type: import_constants.IMAGE_TYPE
            });
          }
          URL.revokeObjectURL(video.src);
          resolve(metadata);
        },
        import_constants.IMAGE_TYPE,
        import_constants.IMAGE_QUALITY
      );
    };
    video.onloadedmetadata = () => {
      hasMetadata = true;
      tryResolve();
    };
    video.onseeked = () => {
      hasSeeked = true;
      tryResolve();
    };
    video.src = URL.createObjectURL(file);
  });
};
var createAudioMetadata = async (file) => {
  return new Promise((resolve) => {
    const audio = document.createElement("audio");
    audio.preload = "metadata";
    audio.src = URL.createObjectURL(file);
    audio.onloadedmetadata = () => {
      URL.revokeObjectURL(audio.src);
      resolve({
        duration: audio.duration,
        bitrate: file.size / audio.duration
      });
    };
  });
};
var getMediaMetadata = async (file) => {
  if (file.type.startsWith(import_constants.MEDIA_TYPES.VIDEO)) {
    return createVideoMetadata(file);
  }
  if (file.type.startsWith(import_constants.MEDIA_TYPES.AUDIO)) {
    return createAudioMetadata(file);
  }
  return null;
};
var genFileListByString = (value) => {
  if (!value)
    return [];
  return [{
    uid: generateUid(),
    name: getFileName(value),
    status: "done",
    url: value
  }];
};
var createMultilingualData = (value) => {
  return import_constants.SUPPORTED_LANGUAGES.reduce((acc, lang) => {
    acc[lang] = value;
    return acc;
  }, {});
};
var createMultilingualFileList = (value) => {
  return import_constants.SUPPORTED_LANGUAGES.reduce((acc, lang) => {
    acc[lang] = genFileListByString(value);
    return acc;
  }, {});
};
var handleMultilingualSingleFile = (value, index = 1) => ({
  uid: `-${index}`,
  name: getFileName(value),
  status: "done",
  url: value,
  multilingualFileList: createMultilingualFileList(value),
  multilingual: createMultilingualData(value)
});
var handleMultilingualObject = (value, index = 1) => {
  const defaultUrl = value.original || value.en || value["zh-CN"] || value["zh-HK"];
  return {
    uid: `-${index}`,
    name: getFileName(defaultUrl),
    status: "done",
    url: defaultUrl,
    multilingual: value,
    multilingualFileList: import_constants.SUPPORTED_LANGUAGES.reduce((acc, lang) => {
      acc[lang] = genFileListByString(value[lang]);
      return acc;
    }, {})
  };
};
var getDefaultFileList = (value, options) => {
  if (!value)
    return [];
  if (Object.values(value).filter((item) => !!item).length === 0)
    return [];
  const { enableMultilingual, multiple } = options;
  if (enableMultilingual) {
    if ((0, import_utils.isString)(value)) {
      return [handleMultilingualSingleFile(value)];
    }
    if (Array.isArray(value)) {
      return value.map((item, index) => {
        if ((0, import_utils.isString)(item)) {
          return handleMultilingualSingleFile(item, index);
        }
        if ((0, import_utils.isPlainObject)(item)) {
          return handleMultilingualObject(item, index);
        }
        return [];
      }).flat();
    }
    if ((0, import_utils.isPlainObject)(value)) {
      return [handleMultilingualObject(value)];
    }
  }
  if (multiple && Array.isArray(value)) {
    return value.map((url, index) => ({
      uid: `-${index}`,
      name: getFileName(url),
      status: "done",
      url
    }));
  }
  if ((0, import_utils.isString)(value)) {
    return [{
      uid: import_constants.DEFAULT_UID,
      name: getFileName(value),
      status: "done",
      url: value
    }];
  }
  return [];
};
var getFileMetadataParams = (file) => {
  if (!file.metadata)
    return {};
  const metadataParams = {};
  const metadataKeys = ["width", "height", "duration", "bitrate"];
  metadataKeys.forEach((key) => {
    var _a;
    if (((_a = file.metadata) == null ? void 0 : _a[key]) !== void 0) {
      metadataParams[`metadata[${key}]`] = file.metadata[key];
    }
  });
  return metadataParams;
};
var isValueEqual = (value, fileListValue) => {
  if (!value && !fileListValue)
    return true;
  if (!value || !fileListValue)
    return false;
  if (Array.isArray(value) && Array.isArray(fileListValue)) {
    if (value.length !== fileListValue.length)
      return false;
    return value.every((v, i) => {
      if (typeof v === "object") {
        return JSON.stringify(v) === JSON.stringify(fileListValue[i]);
      }
      return v === fileListValue[i];
    });
  }
  if (typeof value === "object" && typeof fileListValue === "object") {
    return JSON.stringify(value) === JSON.stringify(fileListValue);
  }
  return value === fileListValue;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  checkFileCount,
  createMultilingualData,
  createMultilingualFileList,
  genFileListByString,
  generateUid,
  getDefaultFileList,
  getFileMetadataParams,
  getFileName,
  getFileType,
  getMediaMetadata,
  getPointSuffix,
  getSuffix,
  isValueEqual
});
