/**
    image to webp
    @사용법
    const webpFile = await convertImageToWebp(this.attach);
    attach = webpFile[0];
*/
import { imageConverter } from 'upload-images-converter';

const calculateAspectRatioSize = (originWidth, originHeight, maxWidthOrHeight) => {
    const maxSize = Math.max(originWidth, originHeight);

    if (maxSize <= maxWidthOrHeight) {
        return { width: originWidth, height: originHeight };
    }

    if (originWidth === maxSize) {
        const width = maxWidthOrHeight;
        const height = Number(((originHeight * maxWidthOrHeight) / originWidth).toFixed(1));

        return { width, height };
    }

    const width = Number(((originWidth * maxWidthOrHeight) / originHeight).toFixed(1));
    const height = maxWidthOrHeight;

    return { width, height };
};

const getImageSize = (imageFile) => {
    return new Promise((resolve, reject) => {
        if (!imageFile) {
            resolve({ originWidth: 100, originHeight: 100 }); // Default size
            return;
        }

        const img = new Image();
        const reader = new FileReader();

        img.onload = () => {
            const originWidth = img.naturalWidth;
            const originHeight = img.naturalHeight;

            resolve({ originWidth, originHeight });
        };

        reader.onload = () => {
            img.src = reader.result?.toString() ?? '';
        };

        reader.readAsDataURL(imageFile);

        img.onerror = error => {
            reject(error);
        };

        reader.onerror = error => {
            reject(error);
        };
    });
};

const convertImageToWebp = async (imageFile) => {
    if (typeof imageFile === 'string' || imageFile.name.split('.')[1].toLowerCase() === 'webp') {
        return imageFile;
    }

    if (!imageFile || !(imageFile instanceof Blob)) {
        const placeholderBlob = new Blob([], { type: 'image/webp' });
        const placeholderFile = new File([placeholderBlob], `${Date.now().toString()}.webp`);
        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(placeholderFile);
        return dataTransfer.files;
    }

    try {
        const { originWidth, originHeight } = await getImageSize(imageFile);
        const maxWidthOrHeight = 1200;

        const { width, height } = calculateAspectRatioSize(originWidth, originHeight, maxWidthOrHeight);

        const compressedBlob = await imageConverter({ files: [imageFile], width, height });

        const outputWebpFile = new File([compressedBlob[0]], `${Date.now().toString()}.webp`);

        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(outputWebpFile);

        return dataTransfer.files;
    } catch (error) {
        console.error('HEIC 변환 오류:', error);
        throw error;
    } finally {
        //로딩이 있다면 여기서 끝내자
    }

};

export { convertImageToWebp };
