import { FilePreviewEvent, FilePreviewErrorMessages, FilePreviewState } from "../types";
export const generatePreviewUrl = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        if (file) {
            reader.readAsDataURL(file);
        }
        else {
            reject(FilePreviewErrorMessages.NO_FILE_SELECTED);
        }
        reader.onload = () => {
            const previewUrl = reader.result;
            resolve(previewUrl);
        };
        reader.onerror = (error) => {
            reject(FilePreviewErrorMessages.UNABLE_TO_GENEARTE_URL);
        };
    });
};
export const removeFile = (removeFile, e, originalUrl) => {
    if (e.target) {
        e.target.dispatchEvent(new CustomEvent(FilePreviewEvent.NILE_REMOVE, {
            detail: { value: removeFile, url: originalUrl },
            bubbles: true,
            composed: true,
        }));
    }
};
export const cancelFileUpload = (file, e, nileFilePreview) => {
    if (e.target) {
        e.target.dispatchEvent(new CustomEvent(FilePreviewEvent.NILE_CANCEL_UPLOAD, {
            detail: { file: file },
            bubbles: true,
            composed: true,
        }));
        nileFilePreview.state = FilePreviewState.ERROR;
        nileFilePreview.errorMessage = FilePreviewErrorMessages.UPLOAD_CANCEL;
        nileFilePreview.requestUpdate();
    }
};
export const formatFileSize = (bytes) => {
    const kb = bytes / 1000;
    const mb = bytes / 1000000;
    const gb = bytes / 1000000000;
    if (gb >= 1)
        return gb.toFixed(2) + ' GB';
    if (mb >= 1)
        return mb.toFixed(2) + ' MB';
    if (kb >= 1)
        return kb.toFixed(2) + ' KB';
    return bytes + ' B';
};
export const getFileType = (file, showFileType) => {
    if (showFileType) {
        return file.name.split('.').pop() || '';
    }
    const type = file.type || '';
    const parts = type.split('/');
    const subtype = parts[1] || '';
    return subtype.toUpperCase();
};
export const truncateString = (nileFilePreview) => {
    if (nileFilePreview.variant === 'vertical' && nileFilePreview.errorMessage.length > 34) {
        nileFilePreview.isStringTruncated = true;
        nileFilePreview.requestUpdate();
    }
    else if (nileFilePreview.variant === 'horizontal' && nileFilePreview.errorMessage.length > 96) {
        nileFilePreview.isStringTruncated = true;
        nileFilePreview.requestUpdate();
    }
};
export const isRealImage = (file) => {
    return new Promise((resolve) => {
        const blob = new Blob([file], { type: file.type });
        const url = URL.createObjectURL(blob);
        const img = new Image();
        img.onload = () => {
            URL.revokeObjectURL(url);
            resolve(true);
        };
        img.onerror = () => {
            URL.revokeObjectURL(url);
            resolve(false);
        };
        img.src = url;
    });
};
//# sourceMappingURL=nile-file-preview.util.js.map