/*
 * WaterCheck.java
 *
 * Created on April 21, 2003, 9:07 PM
 */

import java.awt.*;
import java.lang.Math;
import java.awt.event.*;
import java.applet.*;
import java.applet.Applet;
import java.io.*;
import java.net.*;
import java.util.*;
import java.beans.*;
import java.awt.image.*;

/**
 *  Checks for water on NIMA downloaded images
 *
 * @author  Nick Cole
 */
public class WaterCheck {
    private int pixels[];               //used to detect water
    private PixelGrabber pg;
    
    /** Creates a new instance of WaterCheck */
    public WaterCheck() {
    }
    
    //initializes the pixel grabber
    public boolean initGrabber(Image img, ImageObserver callingApp){
        pixels = new int[img.getWidth(callingApp) * img.getHeight(callingApp)];
        pg = new PixelGrabber(img, 0, 0, img.getWidth(callingApp), img.getHeight(callingApp),
            pixels, 0, img.getWidth(callingApp));
        try {
            pg.grabPixels();
        } catch (InterruptedException e) {
            System.err.println("ERROR: interrupted waiting for pixels!");
            return false;
        }
        if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
            System.err.println("ERROR: image fetch aborted or errored");
            return false;
        }
        
        return true;
    }
    
    //check to see if a pixel is water
    private boolean checkForWater( int x, int y, int pixel ){
        int alpha = (pixel >> 24) & 0xff;
        int red   = (pixel >> 16) & 0xff;
        int green = (pixel >>  8) & 0xff;
        int blue  = (pixel      ) & 0xff;

        if( red == 159 && green == 159 && blue == 159  ){
            return true;
        } else {
            return false;
        }

    }
    
    /* returns true if a pixel is inside of water
     * @param x - an int which is the offset into the image
     * @param y - an int which is the offset into the image (should be zero)
     * @param w - an int the width of an image
     * @param h - an int the height of the image
     * @param testI - the x of the coordinate to be tested
     * @param testJ - the y of the coordinate to be tested
     */
    public boolean handlepixels( int x, int y, int w, int h, int testI, int testJ) {

        try{
           return checkForWater(x+testI, y+testJ, pixels[testJ * w + testI]);
        } catch( ArrayIndexOutOfBoundsException e ){
             System.out.println( "ERROR: Pixel Grabber array out of bounds." );
             System.out.println( "testI: " + testI + " testJ: " + testJ );
             System.out.println( "w: " + w + " h: " + h );
            
             return false;
        }     
    }
    
}
