require("../../../../_virtual/_rolldown/runtime.js");
const require_index = require("../../../../locales/index.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_constants = require("./constants.js");
let _pisell_utils = require("@pisell/utils");
//#region src/components/dataSourceComponents/fields/Upload/utils.tsx
const generateUid = () => {
	return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
};
const getSuffix = (name) => name.split(".").pop() || "";
const getPointSuffix = (name) => `.${getSuffix(name)}`;
const getFileType = (name) => getPointSuffix(getSuffix(name));
const getFileName = (url) => {
	const parts = url.split("/");
	return parts[parts.length - 1] || "";
};
const checkFileCount = ({ multiple, minCount, maxCount, valueLength }) => {
	if (!multiple) return { success: true };
	if (minCount === maxCount && valueLength !== minCount) return {
		success: false,
		message: require_index.getText("pisell-upload-count-error")(minCount)
	};
	if (minCount !== maxCount && (valueLength < minCount || valueLength > maxCount)) return {
		success: false,
		message: require_index.getText("pisell-upload-count-error")(`${minCount}-${maxCount}`)
	};
	return { success: true };
};
const createVideoMetadata = function() {
	var _ref = require_asyncToGenerator._asyncToGenerator(function* (file) {
		return new Promise((resolve, reject) => {
			const video = document.createElement("video");
			const canvas = document.createElement("canvas");
			video.preload = "metadata";
			let hasMetadata = false;
			let hasSeeked = false;
			const tryResolve = () => {
				if (!hasMetadata || !hasSeeked) {
					reject();
					console.log("没有元数据或没有seeked");
					return;
				}
				canvas.width = video.videoWidth;
				canvas.height = video.videoHeight;
				const ctx = canvas.getContext("2d");
				ctx === null || ctx === 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: require_constants.IMAGE_TYPE });
					URL.revokeObjectURL(video.src);
					resolve(metadata);
				}, require_constants.IMAGE_TYPE, require_constants.IMAGE_QUALITY);
			};
			video.onloadedmetadata = () => {
				hasMetadata = true;
				tryResolve();
			};
			video.onseeked = () => {
				hasSeeked = true;
				tryResolve();
			};
			video.src = URL.createObjectURL(file);
		});
	});
	return function createVideoMetadata(_x) {
		return _ref.apply(this, arguments);
	};
}();
const createAudioMetadata = function() {
	var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (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
				});
			};
		});
	});
	return function createAudioMetadata(_x2) {
		return _ref2.apply(this, arguments);
	};
}();
const getMediaMetadata = function() {
	var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (file) {
		if (file.type.startsWith(require_constants.MEDIA_TYPES.VIDEO)) return createVideoMetadata(file);
		if (file.type.startsWith(require_constants.MEDIA_TYPES.AUDIO)) return createAudioMetadata(file);
		return null;
	});
	return function getMediaMetadata(_x3) {
		return _ref3.apply(this, arguments);
	};
}();
const genFileListByString = (value) => {
	if (!value) return [];
	return [{
		uid: generateUid(),
		name: getFileName(value),
		status: "done",
		url: value
	}];
};
const createMultilingualData = (value) => {
	return require_constants.SUPPORTED_LANGUAGES.reduce((acc, lang) => {
		acc[lang] = value;
		return acc;
	}, {});
};
const createMultilingualFileList = (value) => {
	return require_constants.SUPPORTED_LANGUAGES.reduce((acc, lang) => {
		acc[lang] = genFileListByString(value);
		return acc;
	}, {});
};
const handleMultilingualSingleFile = (value, index = 1) => ({
	uid: `-${index}`,
	name: getFileName(value),
	status: "done",
	url: value,
	multilingualFileList: createMultilingualFileList(value),
	multilingual: createMultilingualData(value)
});
const handleMultilingualObject = (value, index = 1) => {
	const defaultUrl = value.original || value.en || value["zh-CN"] || value["zh-HK"] || value["ja"] || value["pt"];
	return {
		uid: `-${index}`,
		name: getFileName(defaultUrl),
		status: "done",
		url: defaultUrl,
		multilingual: value,
		multilingualFileList: require_constants.SUPPORTED_LANGUAGES.reduce((acc, lang) => {
			acc[lang] = genFileListByString(value[lang]);
			return acc;
		}, {})
	};
};
const getDefaultFileList = (value, options) => {
	if (!value) return [];
	if (Object.values(value).filter((item) => !!item).length === 0) return [];
	const { enableMultilingual, multiple } = options;
	if (enableMultilingual) {
		if ((0, _pisell_utils.isString)(value)) return [handleMultilingualSingleFile(value)];
		if (Array.isArray(value)) return value.map((item, index) => {
			if ((0, _pisell_utils.isString)(item)) return handleMultilingualSingleFile(item, index);
			if ((0, _pisell_utils.isPlainObject)(item)) return handleMultilingualObject(item, index);
			return [];
		}).flat();
		if ((0, _pisell_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, _pisell_utils.isString)(value)) return [{
		uid: "-1",
		name: getFileName(value),
		status: "done",
		url: value
	}];
	return [];
};
const getFileMetadataParams = (file) => {
	if (!file.metadata) return {};
	const metadataParams = {};
	[
		"width",
		"height",
		"duration",
		"bitrate"
	].forEach((key) => {
		var _file$metadata;
		if (((_file$metadata = file.metadata) === null || _file$metadata === void 0 ? void 0 : _file$metadata[key]) !== void 0) metadataParams[`metadata[${key}]`] = file.metadata[key];
	});
	return metadataParams;
};
const 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;
};
const getBaseTime = (size) => {
	const MB = 1024 * 1024;
	if (size < MB) return 1e3;
	if (size < 5 * MB) return 2e3;
	if (size < 20 * MB) return 4e3;
	return 8e3;
};
//#endregion
exports.checkFileCount = checkFileCount;
exports.createMultilingualData = createMultilingualData;
exports.createMultilingualFileList = createMultilingualFileList;
exports.getBaseTime = getBaseTime;
exports.getDefaultFileList = getDefaultFileList;
exports.getFileMetadataParams = getFileMetadataParams;
exports.getFileType = getFileType;
exports.getMediaMetadata = getMediaMetadata;
exports.getPointSuffix = getPointSuffix;
exports.isValueEqual = isValueEqual;
