import { getFileSignRequest, uploadFileConfirmRequest } from "../api/file";
import { handleError } from "../store/dialog";
import { configStore } from "../store/store";
import { getSignedS3Request } from "./axios";
import { MAX_FILE_SIZE } from "./constant";
const isImageFile = (file) => file.type.startsWith('image/');
export const uploadFile = async ({ file, filename = 'untitled', folder }) => {
    const businessId = configStore.get('businessId');
    const fileToUpload = await processFile(file);
    const data = {
        'file-name': `${businessId}_${Date.now()}_${filename.replaceAll(' ', '-')}.${(fileToUpload && fileToUpload.name && fileToUpload.name.split('.').pop()) || ''}`,
        'file-type': fileToUpload.type || 'application/octet-stream',
        'folder-name': folder,
    };
    try {
        let url = await getSignedRequest(data, fileToUpload);
        url = encodeURI(url || '');
        if (typeof url !== 'undefined') {
            return url;
        }
    }
    catch (error) {
        handleError(error);
    }
};
const getSignedRequest = async (value, file) => {
    try {
        const response = await getSignedS3Request(value);
        if (response) {
            const { result } = response;
            const uploadedResponse = await uploadFileToS3(result, file);
            return uploadedResponse;
        }
    }
    catch (error) {
        handleError(error);
    }
};
const uploadFileToS3 = async ({ signedRequest, url }, file, forcePublicRead = true) => {
    return new Promise((resolve, reject) => {
        const formData = new FormData();
        if (forcePublicRead) {
            formData.append('acl', 'public-read');
        }
        Object.keys(signedRequest.fields).forEach(key => {
            formData.append(key, signedRequest.fields[key]);
        });
        formData.append('file', file);
        const xhr = new XMLHttpRequest();
        xhr.open('POST', signedRequest.url, true);
        xhr.send(formData);
        xhr.onload = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200 || xhr.status === 204) {
                    resolve(`${url}`);
                }
                else {
                    reject('Could not upload file.');
                }
            }
        };
    });
};
export const uploadFileService = async ({ file, filename = 'untitled', usageType = 'chat' }) => {
    try {
        const fileToUpload = await processFile(file);
        const data = {
            // fileName: `${Date.now()}_${filename.replaceAll(' ', '-')}`,
            fileName: filename,
            usageType,
        };
        const { id, url, key } = await getFileSign(data, fileToUpload);
        if (usageType) {
            await uploadFileConfirmRequest(id);
        }
        return { id, url, key };
    }
    catch (error) {
        handleError(error);
    }
};
const getFileSign = async (value, file) => {
    let result = { id: '', url: '', key: '' };
    try {
        const response = await getFileSignRequest(value);
        if (response) {
            const { id, url, fields } = response;
            const signBody = {
                url,
                signedRequest: {
                    fields,
                    url,
                },
            };
            const uploadedResponse = await uploadFileToS3(signBody, file, false);
            result = { id, url: encodeURI(uploadedResponse || ''), key: fields.key };
        }
    }
    catch (error) {
        handleError(error);
    }
    return result;
};
export const useResizeImage = (file, maxWidth = 500, maxHeight = 500) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = event => {
            const img = new Image();
            img.src = event.target ? event.target.result : '';
            img.onload = () => {
                const { width, height } = img;
                let newWidth = width;
                let newHeight = height;
                if (width > maxWidth) {
                    newWidth = maxWidth;
                    newHeight = (height / width) * maxWidth;
                }
                if (newHeight > maxHeight) {
                    newHeight = maxHeight;
                    newWidth = (width / height) * maxHeight;
                }
                const canvas = document.createElement('canvas');
                canvas.width = newWidth;
                canvas.height = newHeight;
                const ctx = canvas.getContext('2d');
                if (ctx) {
                    ctx.drawImage(img, 0, 0, newWidth, newHeight);
                }
                canvas.toBlob(blob => {
                    if (blob) {
                        const resizedFile = new File([blob], file.name, {
                            type: file.type,
                            lastModified: file.lastModified,
                        });
                        resolve(resizedFile);
                    }
                    else {
                        reject(new Error('Failed to resize the image.'));
                    }
                }, file.type);
            };
        };
        reader.onerror = event => {
            console.log('error', event);
            reject(new Error('Failed to read the image.'));
        };
        reader.readAsDataURL(file);
    });
};
const processFile = async (file) => {
    if (file.size > MAX_FILE_SIZE) {
        throw new Error('File size exceeds maximum limit of 25MB');
    }
    if (!configStore.get('isProduction') && isImageFile(file)) {
        try {
            return await useResizeImage(file);
        }
        catch {
            return file;
        }
    }
    return file;
};
export const handleGetMediaUrlFromSignKey = (key) => {
    return `https://d16rfd3rgmqmmh.cloudfront.net/${key}`;
};
