import se.datadosen.jalbum.JAFilter;
import java.awt.*;
import java.awt.image.BufferedImage;
import se.datadosen.util.*;
import javax.swing.ImageIcon;
import java.io.*;
import java.net.*;


/**
 * Title:        JAlbum image filter that rotates images
 * Copyright:    Copyright (c) 2003
 * Company:      Datadosen
 * @author David Ekholm
 * @version 1.0
 */

public class RotationFilter implements JAFilter {

    // Default image

    private Color bgColor = new Color(255,255,255,255);
    private boolean antialias = true;
    private int angdeg = 15;
    private boolean random = false;
    private String background;
    private ImageIcon bgIcon;

		// Implements JAFilter
    public String getName() {
        return "Rotation filter";
    }

		// Implements JAFilter
    public String getDescription() {
        return "Rotates images a fixed amount or randomly";
    }

		// Implements JAFilter
    public BufferedImage filter(BufferedImage bi, java.util.Map vars) {
		int w = bi.getWidth();
		int h = bi.getHeight();
		int finalAngle = angdeg;
		if (random) finalAngle = (int)(Math.random() * (angdeg*2)) - angdeg;
		double a = Math.toRadians(finalAngle);

		int newW = (int)(Math.abs(w * Math.cos(a)) + Math.abs(h * Math.sin(a)));
		int newH = (int)(Math.abs(w * Math.sin(a)) + Math.abs(h * Math.cos(a)));

		// create new image
		BufferedImage newImage = new BufferedImage(newW, newH,BufferedImage.TYPE_INT_RGB);
		Graphics2D g = newImage.createGraphics();
		if (antialias)
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

		g.setColor(bgColor);
		g.fillRect(0, 0, newW, newH);
		if (bgIcon != null) g.drawImage(bgIcon.getImage(), 0, 0, null);

		g.rotate(a,newW/2,newH/2);
		//g.translate((newW-w)/2,(newH-h)/2);
		g.drawImage(bi, (newW-w)/2, (newH-h)/2, null);

		return newImage;
    }

    public void setBgColor(Color color) {
        this.bgColor = bgColor;
    }

    public void setBgColor(String htmlColor) {
        this.bgColor = Colors.getHTMLColor(htmlColor);
    }

    public Color getBgColor() {
        return bgColor;
    }

    public void setBackground(String imageURL) throws IOException {
        URL url = new URL(imageURL);
        bgIcon = new ImageIcon(url);
        background = imageURL;
    }

    public String getBackground() {
        return background;
    }

    public void setAntialias(boolean newAntialias) {
        antialias = newAntialias;
    }
    public boolean isAntialias() {
        return antialias;
    }

    public int getAngle() {
		return angdeg;
	}

	public void setAngle(int angdeg) {
		this.angdeg = angdeg;
	}

    public void setRandom(boolean randomRotation) {
        this.random = randomRotation;
    }
    public boolean isRandom() {
        return random;
    }

}