/* $Id: Query.java 432 2011-10-17 17:46:48Z shayashi $ */
package image_search;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.io.File;

import smart_gs.image_search.logical.GSQuery;
import smart_gs.logical.Spread;
import smart_gs.util.ImageCropper;

public class Query {
	
	protected File dscFile;         
	protected Rectangle rectangle;  
	protected Image image;
	protected Spread spread;
	protected Image queryImage;
	protected Image queryImageWithTransformation;
	
	public Spread getSpread() {
		return spread;
	}
	public void setSpread(Spread spread) {
		this.spread = spread;
	}
	public Query(Image image,File dscFile,Rectangle rectangle){
		this.spread = null; /* no spread case */
		this.dscFile = dscFile;
		this.rectangle = rectangle;
		this.image = image;
		this.queryImage = null;
		this.queryImageWithTransformation = null;
	}
//	If the query given by a rectangle of a spread, a transformation might be
//	necessary to get the right queryImage from the rectangle. Note that the
//	rectangle of Query is for dsc file not for image file.
	public Query(Spread spread, File dscFile,Rectangle rectangle){
		this.dscFile = dscFile;
		this.rectangle = rectangle;
		this.image = spread.getImage();
		this.spread = spread;
		this.queryImage = null;
		this.queryImageWithTransformation = null;
	}
	public Image getQueryImage(){
		if (this.queryImage == null) {
			this.queryImage = new ImageCropper(this.image,rectangle).crop();
		}
		return this.queryImage;
	}
	public Image getQueryImageWithTransformation(){
		if (spread == null){
			System.out.println("getQueryImageWithTransformation is applicable only to Spread image");
			return null;
		} else if (!spread.isTransformationIsNecessary()) {
			return getQueryImage();
		} else {
			if (this.queryImageWithTransformation == null) {
				AffineTransform affineTransformFromDSCToImage = spread.getAffineTranformFromDscToImg();
				Shape shapeMapped = affineTransformFromDSCToImage.createTransformedShape((Rectangle2D)rectangle);
				Rectangle rectangleMapped = shapeMapped.getBounds();
				this.queryImageWithTransformation = new ImageCropper(this.image,rectangleMapped).crop();
			}
			return this.queryImageWithTransformation;
		}
	}
	public File getDSCFile(){
		return this.dscFile;
	}
	public Rectangle getRectangle(){
		return this.rectangle;
	}
	public void setRectangle(Rectangle rectangle){
		this.rectangle = rectangle;
	}
}
