/* $Id: RESearch.java 125 2011-03-09 09:49:51Z ohura $ */
package smart_gs.image_search.research;

import java.util.ArrayList;
import java.util.List;

import smart_gs.image_search.SearchQueryAction;
import smart_gs.image_search.logical.GSQuery;
import smart_gs.image_search.logical.SearchResult;
import smart_gs.image_search.research.swingui.REImageSearchDialog;
import smart_gs.logical.Spread;


public class RESearch {
	
	private List<GSQuery> queries;
	private List<SearchResultSet> results;
	private List<Spread> spreadsToSearch;
	private REImageSearchDialog dialog;
	
	private SearchFilter filter;
	
	public RESearch(REImageSearchDialog dialog,List<GSQuery> queries,List<Spread> spreadsToSearch) {
		this.queries = queries;
        this.spreadsToSearch = spreadsToSearch;
		this.results = new ArrayList<SearchResultSet>();
		this.dialog = dialog;
		if(this.dialog.isLineSelected()){
			this.filter = new LineFilter(this.dialog.getLineNumber());
		}
		else{
			this.filter = new SpreadFilter();
		}
	}
	public List<GSQuery> getQueries(){
		return this.queries;
	}
	public List<SearchResultSet> getResults(){
		return this.results;
	}
	public void execute(){
		List<List<SearchResult>> res = new ArrayList<List<SearchResult>>();
		for(int i=0;i<queries.size();i++){
			SearchQueryAction searcher = new SearchQueryAction(queries.get(i),spreadsToSearch);
			searcher.execute();
			List<SearchResult> result = searcher.getResults();
			res.add(result);
		}
		/*
		 *  filtering 処理
		 */
		this.results = this.filter.filtering(res);
		/*
		 * sorting 処理
		 */
		this.results = this.simpleSorting(this.results);
	}
	public List<SearchResultSet> simpleSorting(List<SearchResultSet> result){
		double minScore = -1;
		int minIndex = -1;
		int size = result.size();
		for(int i=0;i<size;i++){
			minScore = result.get(i).getScore();
			minIndex = i;
			for(int j=i;j<result.size();j++){
				double score = result.get(j).getScore();
				if(score < minScore){
					minIndex = j;
				}
			}
			SearchResultSet set = result.get(minIndex);
			result.remove(minIndex);
			result.add(i,set);
		}
		return result;
	}
}
