package com.cringe_studios.christmastreescanning.scanning.image_scanning;

import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.Arrays;

public class SingleRGBImageScanner extends RGBImageScanner {
	
	private GrayscaleImageScanner theRealScanner; // 🤫 this class is not doing actual work... that class is
	
	//private static BufferedImage deepCopy(BufferedImage bi) {
	//	 ColorModel cm = bi.getColorModel();
	//	 boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
	//	 WritableRaster raster = bi.copyData(null);
	//	 return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
	//}
	
	@Override
	protected BufferedImage[] toGrayscale(BufferedImage rgbImage) {
		BufferedImage retImage = new BufferedImage(rgbImage.getWidth(), rgbImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
		
		int[] imageColors = new int[rgbImage.getWidth() * rgbImage.getHeight()];
		rgbImage.getRGB(0, 0, rgbImage.getWidth(), rgbImage.getHeight(), imageColors, 0, rgbImage.getWidth());
		
		imageColors = Arrays.stream(imageColors).map(i -> {
			// Luminosity: Grayscale = 0.3 * R + 0.59 * G + 0.11 * B
			//int alpha = (i >> 24) & 0xFF;
			int red =   (i >> 16) & 0xFF;
			int green = (i >>  8) & 0xFF;
			int blue =  (i      ) & 0xFF;
			int grayscale = Math.min( (int)(0.3 * red + 0.59 * green + 0.11 * blue), 255);
			return (grayscale << 16) | (grayscale << 8) | (grayscale);
		}).toArray();
		
		retImage.setRGB(0, 0, rgbImage.getWidth(), rgbImage.getHeight(), imageColors, 0, rgbImage.getWidth());
		
		return new BufferedImage[]{retImage};
		
	}

	public SingleRGBImageScanner(BufferedImage rgbImage) {
		super();
		BufferedImage grayScaleImage = toGrayscale(rgbImage)[0];
		
		theRealScanner = new GrayscaleImageScanner(grayScaleImage);
	}

	@Override
	public Point2D getBrightestSpot(byte gammaDelta) {
		return theRealScanner.getBrightestSpot();
	}

}
