package de.fred4jupiter.fredbet.service;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import net.coobird.thumbnailator.Thumbnails;

@Service
public class ImageResizingService {

	// TODO: make configurable
	private static final int THUMBNAIL_SIZE = 75;

	private static final int DEFAULT_MAX_SIZE = 1920;

	private static final Logger log = LoggerFactory.getLogger(ImageResizingService.class);

	public byte[] createThumbnail(byte[] imageBinary) {
		return minimizeToSize(imageBinary, THUMBNAIL_SIZE);
	}

	public byte[] minimizeToDefaultSize(byte[] imageBinary) {
		return minimizeToSize(imageBinary, DEFAULT_MAX_SIZE);
	}

	public byte[] minimizeToSize(byte[] imageBinary, int size) {
		try (ByteArrayInputStream byteIn = new ByteArrayInputStream(imageBinary);
				ByteArrayOutputStream byteOut = new ByteArrayOutputStream()) {

			BufferedImage bufferedImage = ImageIO.read(byteIn);
			if (bufferedImage.getWidth() <= size && bufferedImage.getHeight() <= size) {
				log.info(
						"The original image does have the prefered size of {} or is smaller than that. Do not change image size. image with: {}, image height: {}",
						size, bufferedImage.getWidth(), bufferedImage.getHeight());
				return imageBinary;
			}

			Thumbnails.of(bufferedImage).size(size, size).outputFormat("JPEG").toOutputStream(byteOut);
			return byteOut.toByteArray();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}
}

@@ -341,16 +341,124 @@
 bnails;%0D
+%0Aimport net.coobird.thumbnailator.Thumbnails.Builder;%0D%0Aimport net.coobird.thumbnailator.geometry.Positions;%0D
 %0A%0D%0A@Serv
@@ -826,24 +826,104 @@
 UMBNAIL_SIZE
+, builder -%3E builder.crop(Positions.CENTER).size(THUMBNAIL_SIZE, THUMBNAIL_SIZE)
 );%0D%0A%09%7D%0D%0A%0D%0A%09p
@@ -1106,16 +1106,214 @@
 ize) %7B%0D%0A
+%09%09return minimizeToSize(imageBinary, size, builder -%3E builder.size(size, size));%0D%0A%09%7D%0D%0A%09%0D%0A%09public byte%5B%5D minimizeToSize(byte%5B%5D imageBinary, int size, ThumbnailsBuilderCallback byteArrayConverter) %7B%0D%0A
 %09%09try (B
@@ -1857,53 +1857,129 @@
 %0A%09%09%09
-Thumbnails.of(bufferedImage).size(size, size)
+Builder%3CBufferedImage%3E builder = Thumbnails.of(bufferedImage);%0D%0A%09%09%09byteArrayConverter.doWithBuilder(builder);%0D%0A%09%09%09builder
 .out
@@ -2143,11 +2143,155 @@
 %09%7D%0D%0A%09%7D%0D%0A
+%09%0D%0A%09@FunctionalInterface%0D%0A%09private static interface ThumbnailsBuilderCallback %7B%0D%0A%09%09%0D%0A%09%09void doWithBuilder(Builder%3CBufferedImage%3E builder);%0D%0A%09%7D%0D%0A
 %7D%0D%0A

update sizing