package charactermanaj.graphics;

import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.IOException;

import charactermanaj.graphics.filters.ColorConvertFilter;
import charactermanaj.graphics.filters.ColorConvertParameter;
import charactermanaj.graphics.filters.GammaTableFactory;
import charactermanaj.graphics.io.ImageLoader;
import charactermanaj.graphics.io.ImageResource;


public class ColorConvertedImageLoaderImpl implements ColorConvertedImageLoader {

	private static final ColorConvertParameter NULL_COLORCONVPARAM = new ColorConvertParameter();

	private ImageLoader loader;
	
	public ColorConvertedImageLoaderImpl(ImageLoader loader) {
		if (loader == null) {
			throw new IllegalArgumentException();
		}
		this.loader = loader;
	}
	
	public BufferedImage load(ImageResource file, ColorConvertParameter colorConvParam) throws IOException {
		if (file == null) {
			throw new IllegalArgumentException();
		}

		if (colorConvParam == null) {
			colorConvParam = NULL_COLORCONVPARAM;
		}
		
		return colorConvert(loader.load(file), colorConvParam);
	}
	
	protected BufferedImage colorConvert(BufferedImage img, ColorConvertParameter param) {

		float[] factors = {
				param.getFactorR(),
				param.getFactorG(),
				param.getFactorB(),
				param.getFactorA(),
				};
		float[] offsets = {
				param.getOffsetR(),
				param.getOffsetG(),
				param.getOffsetB(),
				param.getOffsetA(),
				};
		RescaleOp rescale_op = new RescaleOp(factors, offsets, null);

		float[] gammas = {
				param.getGammaA(),
				param.getGammaR(),
				param.getGammaG(),
				param.getGammaB(),
				};
		float[] hsbs = {
				param.getHue(),
				param.getSaturation(),
				param.getBrightness()
				};
		ColorConvertFilter colorConvert_op = new ColorConvertFilter(
				param.getColorReplace(),
				hsbs,
				param.getGrayLevel(),
				new GammaTableFactory(gammas)
				);

		img = colorConvert_op.filter(img, null);
		img = rescale_op.filter(img, img);

		return img;
	}

}
