package java.awt.image;


abstract public class RGBImageFilter
  extends ImageFilter
{
	protected ColorModel origmodel;
	protected ColorModel newmodel;
	protected boolean canFilterIndexColorModel;

public RGBImageFilter() {
}

public IndexColorModel filterIndexColorModel( IndexColorModel icm) {
	int trans = icm.getTransparentPixel();
	int ms = icm.getMapSize();
	int newTrans = trans;
	
	int[] newRgbs = new int[ ms];

	for ( int i=0; i<ms; i++) {
		int value = filterRGB( -1, -1, icm.rgbs[i] );
		if ( (newTrans == trans) && (i != trans) ) {
			byte alpha = (byte)(value >> 24);
			if ( alpha != 0xff )
				newTrans = -1;
		}
		newRgbs[i] = value;
	}

	return new IndexColorModel( icm.getPixelSize(), newRgbs, newTrans);
}

abstract public int filterRGB( int x, int y, int rgb );

public void filterRGBPixels( int x, int y, int w, int h, int[] pels, int off, int scan) {
	ColorModel newModel = ColorModel.getRGBdefault();
	int px, py;
	int pIdx = off;
	
	for ( py = 0; py < h; py++) {
		for ( px = 0; px < w; px++)
			pels[pIdx++] = filterRGB( x+px, y+py, pels[pIdx] );
		pIdx += scan-w;
	}
	
	consumer.setPixels( x, y, w, h, newModel, pels, off, scan);
}

public void setColorModel( ColorModel model) {
	ColorModel cm = ColorModel.getRGBdefault();
	
	if ( (model instanceof IndexColorModel) && canFilterIndexColorModel) {
		cm = filterIndexColorModel( (IndexColorModel) model);
		substituteColorModel( model, cm);
	}
	consumer.setColorModel( cm);
}

public void setPixels( int x, int y, int w, int h, ColorModel cm, byte[] pels, int off, int scan) {
	if ( cm == origmodel )
		consumer.setPixels( x, y, w, h, newmodel, pels, off, scan);
	else {
		int px, py;
		int pIdx = 0;
		int[] fPels = new int[w*h];
		
		for ( py = 0; py < h; py++) {
			for ( px = 0; px < w; px++)
				fPels[pIdx++] = cm.getRGB( pels[pIdx+off]);
			pIdx += scan-w;
		}
		
		filterRGBPixels( x, y, w, h, fPels, 0, w);
	}
}

public void setPixels( int x, int y, int w, int h, ColorModel cm, int[] pels, int off, int scan) {
	if ( cm == origmodel )
		consumer.setPixels( x, y, w, h, newmodel, pels, off, scan);
	else {
		int px, py;
		int pIdx = 0;
		int[] fPels = new int[w*h];
		
		for ( py = 0; py < h; py++) {
			for ( px = 0; px < w; px++)
				fPels[pIdx++] = cm.getRGB( pels[pIdx+off]);
			pIdx += scan-w;
		}
		
		filterRGBPixels( x, y, w, h, fPels, 0, w);
	}
}

public void substituteColorModel( ColorModel oldcm, ColorModel newcm) {
	this.origmodel = oldcm;
	this.newmodel  = newcm;
}
}
