/* File: GrayscaleSoln.java
 * ------------------------
 * This program shows how we can use 2D arrays and GImages
 * to modify an image's pixels to make it grayscale.
 */

import java.awt.*;
import java.awt.event.*;
import acm.graphics.*;
import acm.program.*;
import acm.util.*;

public class GrayscaleSoln extends GraphicsProgram {
	private static final String IMG_NAME = "res/stanford.jpg";
	
	public void run() {	
		GImage image = new GImage(IMG_NAME);
		setCanvasSize(image.getWidth(), image.getHeight());
		add(image);
		
		// wait to make grayscale until user clicks
		//waitForClick();  
		
		int[][] pixels = image.getPixelArray();

		// Loop over all pixels and convert them to grayscale
		for (int row = 0; row < pixels.length; row++) {
			for (int col = 0; col < pixels[0].length; col++) {
				int pixel = pixels[row][col];

				int red = GImage.getRed(pixel);
				int green = GImage.getGreen(pixel);
				int blue = GImage.getBlue(pixel);
				
				int luminosity = computeLuminosity(red, green, blue);
				int newPixel = GImage.createRGBPixel(luminosity, luminosity, luminosity);
				pixels[row][col] = newPixel;
			}
		}

		// Update the image with the new pixels
		image.setPixelArray(pixels);
	}
	
	// Calculate the luminosity of a pixel using NTSC formula
	private int computeLuminosity(int r, int g, int b) {
		return GMath.round(0.299 * r + 0.587 * g + 0.114 * b);
	}
}
