/* $Id: ImageSearchPanel.java 344 2011-09-08 13:43:20Z shayashi $ */
package smart_gs.image_search.normal.swingui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

import org.apache.commons.lang.StringUtils;

import smart_gs.dictionary.DictionaryXML;
import smart_gs.dictionary.image.ImageSearchFilterImpl;
import smart_gs.dictionary.image.ImageSearchFilterTypeAImpl;
import smart_gs.dictionary.image.ImageSearchFilterTypeBImpl;
import smart_gs.dictionary.image.ImageSearchFilterTypeCImpl;
import smart_gs.dictionary.viewer.SearchResultDictionaryViewer;
import smart_gs.image_search.SearchQueryAction;
import smart_gs.image_search.logical.GSQuery;
import smart_gs.image_search.logical.QueryBucket;
import smart_gs.image_search.logical.SearchResult;
import smart_gs.image_search.logical.TextType;
import smart_gs.logical.LineSegment;
import smart_gs.logical.Preference;
import smart_gs.logical.Region;
import smart_gs.logical.Spread;
import smart_gs.spread_selection.SetScopePanel;
import smart_gs.util.BmpFileCreator;
import smart_gs.util.CanonicalPathString;
import smart_gs.util.ImageCropper;
import smart_gs.util.DSCFileMaker;

@SuppressWarnings("serial")
public class ImageSearchPanel extends JPanel {
	
	private Image image;
	private Region region;
	private File dscFile;
	private Rectangle rectangle = new Rectangle(0,0,100,50);
	private JLabel imageLabel;	
	/*
	 * spreadの選択のために追加
	 */
	private SetScopePanel scopePanel;
	
	public ImageSearchPanel(){
//		this.makeEditDialog();
		JLabel label = new JLabel("Select region before searching image.");
		this.add(label);
	}

	public ImageSearchPanel(Region region) {
//		super(new JFrame(),"Search Dialog");
		this.setRegion(region);
		this.setRectangle(region);
		this.setDscFile();
		this.setImage(region);
		this.makeImageSearchDialog();
	}
	public void setRegion(Region region){
		this.region = region;
	}
	public void setRectangle(Region region){
		Rectangle2D rect = region.getView().getRectangle2D();
		this.rectangle = new Rectangle((int)rect.getX(),(int)rect.getY(),(int)rect.getWidth(),(int)rect.getHeight());
	}
	public void setDscFile(){
		this.dscFile = this.region.getSpread().getDscFile();
	}
	public void setImage(Region region){
		ImageCropper cropper = new ImageCropper(region);
		this.image = cropper.crop();
	}
	protected void makeImageSearchDialog(){
		this.setLayout(new BorderLayout());
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout());
		JPanel imagePanel =this.createImagePanel();
		mainPanel.add(imagePanel,BorderLayout.CENTER);

		//kazuhiro kobayashi 10/4
		this.scopePanel = new SetScopePanel(true);	
		
		mainPanel.add(scopePanel,BorderLayout.SOUTH);
		
		JPanel buttonPanel = new JPanel();
		JButton ok = new JButton("Search");
		ok.addActionListener(new OKAction());
		buttonPanel.add(ok);
		
		buttonPanel.add(Box.createRigidArea(new Dimension(20,0)));
		
		JButton cancel = new JButton("Cancel");
		cancel.addActionListener(new CancelAction());
		buttonPanel.add(cancel);
		
		this.add(mainPanel,BorderLayout.CENTER);
		this.add(buttonPanel,BorderLayout.SOUTH);
//		this.setLocationRelativeTo(null);
//		this.pack();
	}
	
	protected JPanel createImagePanel(){
		JPanel imagePanel = new JPanel();
		imagePanel.add(Box.createRigidArea(new Dimension(40,0)));
		this.imageLabel = new JLabel(new ImageIcon(this.image));
		imagePanel.add(this.imageLabel);
		imagePanel.add(Box.createRigidArea(new Dimension(10,0)));
		if (TextType.isHorizontal()) {
			imagePanel.add(new JLabel("Search Mode: Horizontal"));
		}else {
			imagePanel.add(new JLabel("Search Mode: Vertical"));
		}
		imagePanel.setBorder(new TitledBorder("query image"));
		return imagePanel;
	}

	private void search(GSQuery query){
//		List<Spread> spreads = this.getSpreadsToSearch();

		List<Spread> spreads = this.scopePanel.getSpreadsToSearch();
		List<Spread> spreadsToSearch = new ArrayList<Spread>();
		for(int i=0;i<spreads.size();i++){
			if(spreads.get(i).hasDscFile()){
				spreadsToSearch.add(spreads.get(i));
			}
		}
		
		SearchQueryAction searchAction = new SearchQueryAction(query,spreadsToSearch);
		// 辞書内の画像検索処理の場合はここで設定する.
		if(this.scopePanel.isImageDictionary()){
			String logic = Preference.getInstance().getSearchImageDictionaryLogic();
			ImageSearchFilterImpl imageSearchFilterImpl;
			if(logic == null){
				logic = "0";
			}
			if(logic.equals("0")){
				imageSearchFilterImpl = new ImageSearchFilterTypeAImpl();
			}else if(logic.equals("1")){
				imageSearchFilterImpl = new ImageSearchFilterTypeBImpl();
			}else if(logic.equals("2")){
				imageSearchFilterImpl = new ImageSearchFilterTypeCImpl();
			}else{
				imageSearchFilterImpl = new ImageSearchFilterTypeAImpl();
			}
			imageSearchFilterImpl.init();
			searchAction.addImageSearchFilter(imageSearchFilterImpl);
		}
		searchAction.execute();
		List<SearchResult> results = searchAction.getResults();
		System.out.println("images to search: " + spreads);
		System.out.println("Search finished. Wait a moment. Search results are going to be displayed...");
		List<GSQuery> queries = new ArrayList<GSQuery>();
		queries.add(query);
		
		QueryBucket bucket = new QueryBucket();
		for(int i=0;i<queries.size();i++){
			bucket.add(queries.get(i));
		}
		//2007/10/11 kazuhiro kobayashi 
		//検索対象のページを表示するため
		if(this.scopePanel.isImageDictionary()){
			SearchResultDictionaryViewer searchResultDictionaryViewer = new SearchResultDictionaryViewer(bucket,results, this.scopePanel.getSelectedPage());
			searchResultDictionaryViewer.setLocationRelativeTo(null);
			searchResultDictionaryViewer.setVisible(true);
		}else{
			new SearchResultViewer(bucket,results, this.scopePanel.getSelectedPage()).setVisible(true);				
		}
//		dispose();
	}
	private class OKAction implements ActionListener{
		
		public void actionPerformed(ActionEvent e) {
			GSQuery query;
			Spread spread = region.getSpread();
			if (spread.isTransformationIsNecessary()){
				AffineTransform affineTransformFromImageToDsc = spread.getAffineTranformFromImgToDsc();
				Shape shapeMapped = affineTransformFromImageToDsc.createTransformedShape((Rectangle2D)rectangle);
				Rectangle rectangleMapped = shapeMapped.getBounds();
				query = new GSQuery(spread,dscFile,rectangleMapped);
			} else {
				query = new GSQuery(spread,dscFile,rectangle);
			}
			try{
				search(query);
			}catch(OutOfMemoryError err){
				JOptionPane.showMessageDialog(null,"Faild to search for memory shortage");
			}
		}
	}
	

	private class CancelAction implements ActionListener{
		public void actionPerformed(ActionEvent e) {
		}
	}
}
