package com.cringe_studios.christmastreescanning.scanning.image_scanning;

import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

import com.cringe_studios.christmastreescanning.scanning.PointInterpolator;

public class GrayscaleImageScanner extends ImageScanner {
	BufferedImage grayScaleImage;

	public GrayscaleImageScanner(BufferedImage grayScaleImage) {
		super();
		this.grayScaleImage = grayScaleImage;
	}

	@Override
	public Point2D getBrightestSpot(byte gammaDelta) {
		int[] imageColors = new int[grayScaleImage.getWidth() * grayScaleImage.getHeight()];

		grayScaleImage.getRGB(0, 0, grayScaleImage.getWidth(), grayScaleImage.getHeight(), imageColors, 0,
				grayScaleImage.getWidth());

		for (int i = 0; i < imageColors.length; i++) {
			imageColors[i] &= 0x0000_00FF; // because the image is grayscale, only one component is needed
		}

		int brightestValue = 0;

		for (int i = 0; i < imageColors.length; i++) {
			if (brightestValue < imageColors[i]) {
				brightestValue = imageColors[i];
			}
		}

		List<Integer> brightSpots = new ArrayList<Integer>();

		for (int i = 0; i < imageColors.length; i++) {
			if (imageColors[i] >= brightestValue - gammaDelta) {
				brightSpots.add(Integer.valueOf(i));
			}
		}

		// The following line might be incorrect; TODO double check and write a test
		Point2D brightPoints[] = brightSpots.stream()
				.map(s -> new Point2D.Double(s.intValue() % grayScaleImage.getWidth(),
						s.intValue() / grayScaleImage.getWidth())) // https://softwareengineering.stackexchange.com/questions/212808/treating-a-1d-data-structure-as-2d-grid
				.toArray(Point2D.Double[]::new);

		Point2D brightestSpot = new PointInterpolator(brightPoints).getCenter();

		return brightestSpot;
	}

}
