"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimelineAssetField = exports.isStaticFileAssetValue = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const no_react_1 = require("remotion/no-react");
const write_static_file_1 = require("../../api/write-static-file");
const Checkmark_1 = require("../../icons/Checkmark");
const import_assets_1 = require("../import-assets");
const ComboBox_1 = require("../NewComposition/ComboBox");
const NotificationCenter_1 = require("../Notifications/NotificationCenter");
const use_static_files_1 = require("../use-static-files");
const comboboxStyle = {
    marginLeft: 8,
    maxWidth: 180,
};
const remoteAssetStyle = {
    display: 'inline-block',
    marginLeft: 8,
    maxWidth: 180,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    verticalAlign: 'middle',
    whiteSpace: 'nowrap',
};
const toFileToken = (name) => {
    return `${no_react_1.NoReactInternals.FILE_TOKEN}${name
        .split('/')
        .map(encodeURIComponent)
        .join('/')}`;
};
const toStaticFileUrl = (fileToken) => {
    return `${window.remotion_staticBase}/${fileToken.slice(no_react_1.NoReactInternals.FILE_TOKEN.length)}`;
};
const isStaticFileAssetValue = (value) => {
    return (typeof value === 'string' && value.startsWith(no_react_1.NoReactInternals.FILE_TOKEN));
};
exports.isStaticFileAssetValue = isStaticFileAssetValue;
const TimelineStaticFileAssetField = ({ propStatus, effectiveValue, onSave, onDragValueChange, onDragEnd, }) => {
    const staticFiles = (0, use_static_files_1.useStaticFiles)();
    const current = String(effectiveValue !== null && effectiveValue !== void 0 ? effectiveValue : '');
    const onSelect = (0, react_1.useCallback)((sourceValue, previewValue) => {
        if (sourceValue === propStatus.codeValue) {
            return;
        }
        onDragValueChange(previewValue);
        onSave(sourceValue).finally(() => {
            onDragEnd();
        });
    }, [propStatus.codeValue, onDragValueChange, onSave, onDragEnd]);
    const upload = (0, react_1.useCallback)(async () => {
        const [file] = await (0, import_assets_1.pickFilesToImport)({ multiple: false });
        if (!file) {
            return;
        }
        const existing = staticFiles.find((candidate) => candidate.name === file.name);
        if (existing && existing.sizeInBytes !== file.size) {
            (0, NotificationCenter_1.showNotification)(`File with name ${file.name} already exists and is different`, 4000);
            return;
        }
        try {
            if (!existing) {
                await (0, write_static_file_1.writeStaticFile)({
                    contents: await file.arrayBuffer(),
                    filePath: file.name,
                });
            }
            const fileToken = toFileToken(file.name);
            onSelect(fileToken, toStaticFileUrl(fileToken));
            if (!existing) {
                (0, NotificationCenter_1.showNotification)(`Created ${file.name} in public folder`, 3000);
            }
        }
        catch (error) {
            (0, NotificationCenter_1.showNotification)(`Could not upload asset: ${error instanceof Error ? error.message : String(error)}`, 4000);
        }
    }, [onSelect, staticFiles]);
    const items = (0, react_1.useMemo)(() => {
        const publicFileItems = staticFiles.map((file) => {
            const fileToken = toFileToken(file.name);
            return {
                type: 'item',
                id: fileToken,
                value: fileToken,
                label: file.name,
                onClick: () => onSelect(fileToken, file.src),
                keyHint: null,
                leftItem: fileToken === current ? jsx_runtime_1.jsx(Checkmark_1.Checkmark, {}) : null,
                subMenu: null,
                quickSwitcherLabel: null,
            };
        });
        return [
            ...publicFileItems,
            { type: 'divider', id: 'upload-asset-divider' },
            {
                type: 'item',
                id: 'upload-asset',
                value: 'upload-asset',
                label: 'Upload…',
                onClick: () => {
                    upload().catch(() => undefined);
                },
                keyHint: null,
                leftItem: null,
                subMenu: null,
                quickSwitcherLabel: null,
                disabled: window.remotion_isReadOnlyStudio,
            },
        ];
    }, [current, onSelect, staticFiles, upload]);
    return (jsx_runtime_1.jsx(ComboBox_1.Combobox, { small: true, title: current, selectedId: current, values: items, style: comboboxStyle }));
};
const TimelineAssetField = (props) => {
    var _a;
    if (props.field.fieldSchema.type !== 'asset') {
        throw new Error('TimelineAssetField rendered for non-asset field');
    }
    if (!(0, exports.isStaticFileAssetValue)(props.effectiveValue)) {
        const remote = String((_a = props.effectiveValue) !== null && _a !== void 0 ? _a : '');
        return (jsx_runtime_1.jsx("span", { style: remoteAssetStyle, title: remote, children: remote }));
    }
    return jsx_runtime_1.jsx(TimelineStaticFileAssetField, { ...props });
};
exports.TimelineAssetField = TimelineAssetField;
