import { PlatformServiceName, } from "@limetech/lime-web-components";
import { FileUpload, MAX_FILE_SIZE, } from "./building-blocks-uploader";
const UPLOAD_COMPLETED = 100;
export class UploadHandler {
    constructor(platform) {
        this.platform = platform;
    }
    /**
     * Handles image paste events in the text editor
     *
     * @param imageInserter - The image inserter with the file info
     * @returns Promise resolving to the uploaded file wrapper or undefined if upload fails
     */
    async handleImagePasted(imageInserter) {
        const fileInfo = imageInserter === null || imageInserter === void 0 ? void 0 : imageInserter.fileInfo;
        if (!fileInfo) {
            return;
        }
        if (!this.validateImageSize(fileInfo)) {
            return;
        }
        imageInserter.insertThumbnail();
        const uploadedFile = await this.createFileUpload(fileInfo);
        const fileUrl = uploadedFile === null || uploadedFile === void 0 ? void 0 : uploadedFile.href;
        const fileId = uploadedFile === null || uploadedFile === void 0 ? void 0 : uploadedFile.fileId;
        if (fileUrl && fileId !== undefined) {
            imageInserter.insertImage(fileUrl);
        }
        else {
            imageInserter.insertFailedThumbnail();
        }
        return uploadedFile;
    }
    /**
     * Extracts a file ID from a image source string.
     *
     * This function parses a URL to find a file ID that appears before
     * '/contents/' at the end of the URL.
     *
     * @param src - The URL string to parse
     * @returns The extracted file ID or undefined if no match is found
     *
     * @example
     * // Returns 123
     * parseFileIdFromSrc('/api/file/123/contents/');
     *
     * @example
     * // Returns 456
     * parseFileIdFromSrc('https://example.com/limepkg-email/api/v1/file/456/contents/');
     *
     * @example
     * // Returns undefined
     * parseFileIdFromSrc('/invalid/url/format/');
     */
    parseFileIdFromSrc(src) {
        if (src) {
            const regex = /\/(\d+)\/contents\/?$/;
            const matches = regex.exec(src);
            if (matches && matches[1]) {
                return Number(matches[1]);
            }
        }
    }
    /**
     * Validates that the image file size is within limits
     *
     * @param fileInfo - The file info to validate
     * @returns True if file size is valid, false otherwise
     */
    validateImageSize(fileInfo) {
        if (!fileInfo.fileContent) {
            return false;
        }
        return fileInfo.fileContent.size <= MAX_FILE_SIZE;
    }
    /**
     * Creates and uploads a file
     *
     * @param fileInfo - The file info to upload
     * @returns Promise resolving to the uploaded file wrapper or undefined if upload fails
     */
    async createFileUpload(fileInfo) {
        var _a;
        if (!fileInfo.fileContent) {
            return;
        }
        const imageFile = new FileUpload(fileInfo.fileContent, this.http);
        await imageFile.initialize();
        const imageUpload = Object.assign(Object.assign({}, fileInfo), { progress: 0, file: imageFile, state: 'added', fileId: undefined, href: undefined, id: fileInfo.id });
        imageFile.onProgress = (progress) => {
            if (imageUpload.progress === 0) {
                imageUpload.state = 'uploading';
            }
            imageUpload.progress = progress;
            if (progress === UPLOAD_COMPLETED) {
                imageUpload.state = 'finalizing';
            }
        };
        const response = await imageFile.upload();
        imageUpload.fileId = response.id;
        imageUpload.filename = response.filename;
        imageUpload.extension = response.extension;
        imageUpload.contentType = response.contentType;
        imageUpload.size = response.size;
        imageUpload.state = 'done';
        imageUpload.href = (_a = response._links) === null || _a === void 0 ? void 0 : _a.contents.href;
        return imageUpload;
    }
    get http() {
        return this.platform.get(PlatformServiceName.Http);
    }
}
