import heic2any from 'heic2any';

/*
const resizedDataURL = await resizeImage(selectedFile);  < 이미지 리사이징
const resizedBlob = dataURLToBlob(resizedDataURL);  < blob url
const resizedFile = new File([resizedBlob], selectedFile.name, { type: fileType }); < File로 변경
*/

const resizeImage = async (file, maxWidth = 800, maxHeight = 600) => {
    if (file.type === 'image/heic') {
        // HEIC 파일 처리
        const convertedFile = await convertHEICToJPG(file);
        return resizeImageFromFile(convertedFile, maxWidth, maxHeight);
    } else {
        // 일반 이미지 파일 처리
        return resizeImageFromFile(file, maxWidth, maxHeight);
    }
}


const convertHEICToJPG = (file) => {
    return new Promise((resolve, reject) => {
        heic2any({
            blob: file,
            toType: 'image/jpeg', // JPG로 변환
        })
            .then(convertedBlob => {
                const convertedFile = new File([convertedBlob], file.name, { type: 'image/jpeg' });
                resolve(convertedFile);
            })
            .catch(error => {
                reject(new Error('HEIC 변환 실패: ' + error.message));
            });
    });
}

const dataURLToBlob = (dataURL) => {
    const byteString = atob(dataURL.split(',')[1]);
    const mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
    const arrayBuffer = new ArrayBuffer(byteString.length);
    const uintArray = new Uint8Array(arrayBuffer);

    for (let i = 0; i < byteString.length; i++) {
        uintArray[i] = byteString.charCodeAt(i);
    }

    return new Blob([arrayBuffer], { type: mimeString });
}


const resizeImageFromFile = (file, maxWidth, maxHeight) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = e => {
            const img = new Image();
            img.onload = () => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                let width = img.width;
                let height = img.height;
                const aspectRatio = width / height;

                if (width > height) {
                    width = Math.min(maxWidth, width);
                    height = width / aspectRatio;
                } else {
                    height = Math.min(maxHeight, height);
                    width = height * aspectRatio;
                }

                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0, width, height);

                // Base64 데이터 반환
                resolve(canvas.toDataURL('image/jpeg'));
            };
            img.onerror = () => reject(new Error('이미지 로드 실패'));
            img.src = e.target.result;
        };
        reader.onerror = () => reject(new Error('파일 읽기 실패'));
        reader.readAsDataURL(file);
    });
}

export { resizeImage , dataURLToBlob};
