/* $Id: Query.java 626 2013-01-13 18:51:36Z shayashi $ */
package image_search;

import java.awt.Dimension;
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;
import sml_editor.logical.LineDirection;

public class Query {
	
	protected File dscFile;         
	protected Rectangle rectangle;  
	protected Image image;
	protected Spread spread;
	protected Image queryImage;
	protected Image queryImageWithTransformation;
	protected LineDirection lineDirection;
	
	public Spread getSpread() {
		return spread;
	}
	public void setSpread(Spread spread) {
		this.spread = spread;
	}
	public Query(Image image,LineDirection direction, 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;
		this.lineDirection = direction;
	}
//	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 Dimension getDimension() {
		if (this.rectangle == null) return null;
		return new Dimension((int)this.rectangle.getX(),(int)this.rectangle.getY());
	}
	public File getDSCFile(){
		return this.dscFile;
	}
	public Rectangle getRectangle(){
		return this.rectangle;
	}
	public void setRectangle(Rectangle rectangle){
		this.rectangle = rectangle;
	}
	
	public LineDirection getLineDirection() {
		return lineDirection;
	}
}
