package com.example.PhotoGallery.Services;

import java.io.FileOutputStream;

import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;

import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

@Service
public class ImageCompression {

    boolean compressImage(String originalImgPath, String compressedImgOutputPath) {

        try {

            File originalFile = new File(originalImgPath);
            BufferedImage original = ImageIO.read(originalFile);

            // Resize manually
            int newWidth = 1000;
            // Prevent division by zero if width is 0
            if (original.getWidth() == 0) return false;
            int newHeight = (original.getHeight() * newWidth) / original.getWidth();
            Image scaled = original.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
            BufferedImage resized = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = resized.createGraphics();
            g2d.drawImage(scaled, 0, 0, null);
            g2d.dispose();

            // Write with compression
            String fileName = originalFile.getName();
            File outFile = new File(compressedImgOutputPath, fileName);
            try (FileOutputStream fos = new FileOutputStream(outFile)) {
                ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
                ImageWriteParam param = jpgWriter.getDefaultWriteParam();
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionQuality(0.7f); // 0.0=lowest, 1.0=highest

                try (ImageOutputStream ios = ImageIO.createImageOutputStream(fos)) {
                    jpgWriter.setOutput(ios);
                    jpgWriter.write(null, new IIOImage(resized, null, null), param);
                }
                jpgWriter.dispose();
                return true;

            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
