/* $Id: ImageSearchPanel.java 669 2013-02-28 14:38:10Z ohura $ */
package smart_gs.image_search.normal.swingui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
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.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.JTextArea;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;

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.GSSearchEngine;
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.Preference;
import smart_gs.logical.Region;
import smart_gs.logical.Spread;
import smart_gs.spread_selection.SetScopePanel;
import smart_gs.swingui.SearchDialog;
import smart_gs.util.DscSearch;
import smart_gs.util.ImageAdjuster;
import smart_gs.util.ImageCropper;
import sml_editor.logical.LineDirection;


@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;	
	private LineDirection lineDirection;
	/*
	 * spreadの選択のために追加
	 */
	private SetScopePanel scopePanel;
	
	private SetSearchOptionPanel searchOptionPanel;
	private SearchDialog searchDialog;

	public ImageSearchPanel(Region region) {
		if (region == null) {
			JLabel label = new JLabel();
			label.setText("<html>" +
					"Select region and try again to do Image Search.<br>" +
					"Or select Global Text Search Tab to do text search globally." + "</html>");
			this.add(label);
			return;
		}

		if(!DscSearch.isDscSearch() && GSSearchEngine.getInstance().isUseExternalEngine()){
			JLabel label = new JLabel();
			label.setText("<html>" + 
					"DscSearch is not available to do Image Search.<br>" +
					"Or select Global Text Search Tab to do text search globally." + "</html>");
			this.add(label);
			return;
		}

		this.region = region;

		Rectangle2D rect = region.getView().getRectangle2D();
		this.rectangle = new Rectangle((int)rect.getX(),(int)rect.getY(),(int)rect.getWidth(),(int)rect.getHeight());

		this.dscFile = this.region.getSpread().getDscFile();

		if (this.dscFile == null) {
			JLabel label = new JLabel();
			label.setText("<html>" +
					"Cannot do Image Search, since no DSC file available.<br>" +
					"Select Global Text Search Tab to do text search globally." + "</html>");
			this.add(label);
			return;
		}
		
		ImageCropper cropper = new ImageCropper(region);
		this.image = cropper.crop();

		this.makeImageSearchDialog();
	}

	protected void makeImageSearchDialog(){
		this.setLayout(new BorderLayout());
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout());
		JPanel imagePanel =this.createImagePanel();
		mainPanel.add(imagePanel,BorderLayout.NORTH);

		//kazuhiro kobayashi 10/4
		this.scopePanel = new SetScopePanel(true);	
		
		mainPanel.add(scopePanel,BorderLayout.WEST);
		
		this.searchOptionPanel = new SetSearchOptionPanel();	
		
		mainPanel.add(searchOptionPanel,BorderLayout.EAST);
		
		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);
	}
	
	protected JPanel createImagePanel(){
		JPanel imagePanel = new JPanel();
		imagePanel.add(Box.createRigidArea(new Dimension(40,0)));
		this.imageLabel = new JLabel(new ImageIcon(ImageAdjuster.adjust(this.image,this.lineDirection,70.0)));
		imagePanel.add(this.imageLabel);
		imagePanel.add(Box.createRigidArea(new Dimension(10,0)));
		if (this.lineDirection == LineDirection.HORIZONTAL) {
			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.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);				
		}
	}
	public void setSearchDialog(SearchDialog searchDialog) {
		this.searchDialog = searchDialog;
	}

	public SearchDialog getSearchDialog() {
		return searchDialog;
	}
	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) {
			//2013/01/18 kukita
			searchDialog.dispose();
		}
	}


}
