/* $Id: LineImageCropper.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.Rectangle;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

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

public class LineImageCropper {
	
	protected int MARGIN_WIDTH = 50;
	
	private int WIDTH = 300;
	private int HEIGHT =60;
	
	private Spread spread;
	private Rectangle2D rect;
	protected Color grayColor;
	
	private int x;
	private int y;
	
	public LineImageCropper(SearchResult result){
		this(result.getSpread(),result.getRectangle());
	}
	public void setMarginWidth(int w){
		this.MARGIN_WIDTH = w;
	}
	public void setWidth(int w){
		this.WIDTH = w;
	}
	public LineImageCropper(GSQuery result){
		this(result.getSpread(),result.getRectangle());
	}
	public LineImageCropper(Spread spread,Rectangle2D rect){
		this.spread = spread;
		this.rect = rect;
		Color color = Color.GRAY.brighter();
		this.grayColor = new Color(color.getRed(),color.getGreen(),color.getBlue(),128);
	}
	
	public BufferedImage crop(){
		Image image = this.spread.getImage();	
		   x = (int)rect.getX()-MARGIN_WIDTH*2;
		   if(x < 0){
			   x = 0;
		   }
		   y = (int)rect.getY();

		   int height = (int)rect.getHeight();		
		
		   BufferedImage bufImage = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
		   Graphics offg = bufImage.getGraphics();
		
		   offg.drawImage(image,0,0,WIDTH,HEIGHT,x,y,x+WIDTH,y+height,null);
		   return bufImage;
				
	}
	/*
	 * 
	 */
	public Image fillRelative(BufferedImage image){
		int w = image.getWidth();
		int h = image.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()-x,(int)rect.getY()-y,(int)rect.getWidth(),(int)rect.getHeight());
		return bImage;
	}
	/*
	 * imageの左上を(0,0)としてrectangleを塗りつぶす
	 */
	public Image fillGray(BufferedImage image,Rectangle rectangle){
		BufferedImage bImage = new BufferedImage(image.getWidth(),image.getHeight(),BufferedImage.TYPE_INT_RGB);
		Graphics og = bImage.getGraphics();
		og.drawImage(image,0,0,image.getWidth(),image.getHeight(),null);
		og.setColor(grayColor);
		og.fillRect((int)rectangle.x,rectangle.y,rectangle.width,rectangle.height);
		return bImage;
	}
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		this.spread.release();
	}
	public int getX(){
		return this.x;
	}
	public int getY(){
		return this.y;
	}
}
