package com.boeing.asl.awt;

import java.awt.Color;
import java.awt.image.*;

/**
 * An image filter analagous to a movie bluescreen.  Wherever
 * pixels of the input image exactly match the screen color,
 * the pixels of the output image will be transparent.  The
 * default screen color is BLACK.
 */

public class BluescreenImageFilter extends RGBImageFilter {
  Color screen = Color.black;
  int screenRGB = screen.getRGB();
  int antiRGB = screenRGB ^ 0xFFFFFFFF;



  public static final int IDENTICAL = 0;
  public static final int PROPORTIONAL = 1;

  int type = IDENTICAL;
    /**
     * Creates a new filter with the given screen color.
     */
  public BluescreenImageFilter (Color color, int type) {
		this();
		setScreenColor(color);
    setType(type);
  }

  /**
   * Creates a new filter with the given screen color.
   */
  public BluescreenImageFilter (Color screen) {
		this();
		setScreenColor(screen);
  }

  /**
   * Creates a new filter with a screen color of black.
   */
  public BluescreenImageFilter () {
		canFilterIndexColorModel = true;
  }


  public int filterRGB (int x, int y, int rgb) {
    if (type == IDENTICAL) {
	  	if (rgb == screenRGB) {
	     	return 0;
	  	} else {
	      return rgb;
	  	}
    } else {
      int blue  = rgb & 0x000000FF;
      int green = (rgb & 0x0000FF00) >> 8;
      int red   = (rgb & 0x00FF0000) >> 16;

      int newRGB = rgb | antiRGB;
      float scale = (float)Math.min(255.0/Math.max(1,red), Math.min(255.0/Math.max(1,green), 255.0/Math.max(blue,1)));

      red   = (int)(scale*red);
      green = (int)(scale*green);
      blue  = (int)(scale*blue);

      int alpha = (int)(255.0f/scale);

      return ((alpha << 24) | (red << 16) | (green << 8) | blue);
    }                          
  }

  /**
   * Set the filter's screen color.
   */
  public void setScreenColor(Color c) {
		screen = c;
		screenRGB = c.getRGB();
     antiRGB = screenRGB ^ 0xFFFFFFFF;
  }

  /**
   * Return the filter's screen color.
   */
  public Color getScreenColor() {
		return screen;
  }

  public void setType(int t) {
    type = t;
  }

  public int getType() {
    return type;
  }
}
