/* $Id: ContextImageCropper.java 125 2011-03-09 09:49:51Z ohura $ */
package smart_gs.image_search;

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

import smart_gs.image_search.logical.SearchResult;
import smart_gs.logical.Spread;

public class ContextImageCropper {
    private final int MARGIN_WIDTH = 150;
    private final int MARGIN_HEIGHT = 100;
    
    private final int WIDTH = 500;
    private final int HEIGHT =150;
    
	private Spread spread;
	private Rectangle2D rect;
	
	protected Color grayColor;
	
	
	public ContextImageCropper(SearchResult result){
		this.spread = result.getSpread();
		this.rect = result.getRectangle();
		Color color = Color.GRAY.brighter();
		this.grayColor = new Color(color.getRed(),color.getGreen(),color.getBlue(),128);
	}
	
	public Image crop(){

		Image image = spread.getImage();
		
		int x = (int)rect.getX()-MARGIN_WIDTH*2;
		if(x < 0){
			x = 0;
		}
		int y = (int)rect.getY() - MARGIN_HEIGHT;
		int width = (int)rect.getWidth()+(MARGIN_WIDTH*4);
		int height = (int)rect.getHeight() + MARGIN_HEIGHT*2;
		
		if(height < 100){
			height = 1000;
		}
		
		int w = spread.getWidth();
		int h = spread.getHeight();
		BufferedImage bImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
		Graphics og = bImage.getGraphics();
		og.drawImage(image,0,0,w,h,null);
		og.setColor(grayColor);
		og.fillRect((int)rect.getX(),(int)rect.getY(),(int)rect.getWidth(),(int)rect.getHeight());
		
		
		BufferedImage bufImage = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
		Graphics offg = bufImage.getGraphics();
		offg.drawImage(bImage,0,0,WIDTH,HEIGHT,x,y,x+width,y+height,null);
		
		return bufImage;
	}
}
