/* $Id: ImageCropper.java 320 2011-08-25 14:13:37Z shayashi $ */
package smart_gs.util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

import smart_gs.GSConstants;
import smart_gs.logical.Region;
import smart_gs.logical.Spread;
/**
 * 
 * @author kazuaki kobayashi
 * 
 *  spread上の特定の領域を表す画像を作成するクラス
 *  
 *  
 */
public class ImageCropper {
	
	private Image image;
	private Rectangle2D rectangle;
	
	private int x;
	private int y;
	private int w;
	private int h;
	
	public ImageCropper(Region region){
		this.image = region.getSpread().getImage();
		this.rectangle = region.getView().getRectangle2D();
		this.x = (int)rectangle.getX();
		this.y = (int)rectangle.getY();
		this.w = (int)rectangle.getWidth();
		this.h = (int)rectangle.getHeight();
	}
	public ImageCropper(Spread spread,Rectangle2D rectangle){
		this.image = spread.getImage();
		this.rectangle = rectangle;
		this.x = (int)rectangle.getX();
		this.y = (int)rectangle.getY();
		this.w = (int)rectangle.getWidth();
		this.h = (int)rectangle.getHeight();
	}
	
	
	public ImageCropper(Image image,Rectangle2D rectangle){
		this.image = image;
		this.rectangle = rectangle;
		this.x = (int)rectangle.getX();
		this.y = (int)rectangle.getY();
		this.w = (int)rectangle.getWidth();
		this.h = (int)rectangle.getHeight();
	}

	public ImageCropper(Image image, Region region) {
		this.image = image;
		this.rectangle = region.getView().getRectangle2D();
		this.x = (int)rectangle.getX();
		this.y = (int)rectangle.getY();
		this.w = (int)rectangle.getWidth();
		this.h = (int)rectangle.getHeight();
	}
	
	public Image crop(){	
		BufferedImage bufImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
		Graphics offg = bufImage.getGraphics();
		offg.drawImage(image,0,0,w,h,x,y,x+w,y+h,null);
		return bufImage;
	}
	public Image crop(int width,int height){
		Image img = this.crop();
		BufferedImage bufImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		Graphics offg = bufImage.getGraphics();
		offg.drawImage(img,0,0,width,height,0,0,w,h,null);
		return bufImage;
	}
	public Image cropForLocalView() {
		int target_size = GSConstants.ELEMENT_VIEW_PANEL_FOR_LOCAL_VIEW_SIZE;
		BufferedImage bufImage = new BufferedImage(target_size,target_size,BufferedImage.TYPE_INT_RGB);
		Graphics offg = bufImage.getGraphics();
		int margin = 20;
		int center_point_x = x + w/2;
		int center_point_y = y + h/2;
		int sx1=0, sy1=0;
		int source_size = 0;
		if (w < target_size - margin && h < target_size - margin) {
			source_size = target_size;
		} else {
			source_size = Math.max(w, h) + 2 * margin;
		}
		sx1 = center_point_x - source_size/2;
		sy1 = center_point_y - source_size/2;
		offg.drawImage(image,0,0,target_size,target_size,sx1,sy1,sx1+source_size,sy1+source_size,null);
		return bufImage;
	}


}
