/* $Id: MultiSearchAction.java 268 2011-07-19 10:00:29Z shayashi $ */
package smart_gs.image_search;

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

import smart_gs.image_search.logical.GSQuery;
import smart_gs.image_search.logical.QueryBucket;
import smart_gs.image_search.logical.SearchResult;
import smart_gs.logical.Spread;

public class MultiSearchAction extends SearchAction{
	
	private List<SearchAction> searchActions;
	
	private int beginCount = 0;
	
	public MultiSearchAction(QueryBucket bucket,List<Spread> spreadsToSearch){
		super(spreadsToSearch);
		this.searchActions = new ArrayList<SearchAction>();
		for(int i=0;i<bucket.size();i++){
			this.searchActions.add(new SearchQueryAction(bucket.get(i),spreadsToSearch));
		}
	}
	
	public MultiSearchAction(List<Spread> spreadsToSearch){
		super(spreadsToSearch);
		this.searchActions = new ArrayList<SearchAction>();
	}
	
	public MultiSearchAction(List<SearchAction> actions,List<Spread> spreadsToSearch){
		super(spreadsToSearch);
		this.searchActions = actions;
	}
	public void setPreviousResults(List<SearchResult> results,int size){
		this.results.addAll(results);
		this.beginCount = size;
	}
	public void add(GSQuery query){
		SearchAction action = new SearchQueryAction(query,this.spreadsToSearch);
		this.searchActions.add(action);
	}
	public void execute() {
		for(int i=this.beginCount;i<searchActions.size();i++){
			searchActions.get(i).execute();
			this.results.addAll(searchActions.get(i).getResults());
		}
		this.sorting();
	}
	@SuppressWarnings("unchecked")
	private void sorting(){
		SearchResult[] arrays = this.results.toArray(new SearchResult[0]);
		Arrays.sort(arrays,new SortCompellator());
		this.results = Arrays.asList(arrays);
		
		
	}
	@SuppressWarnings("unchecked")
	public static List<SearchResult> sorting(List<SearchResult> results){
		SearchResult[] arrays = results.toArray(new SearchResult[0]);
		Arrays.sort(arrays,new SortCompellator());
		return Arrays.asList(arrays);
	}
	@Override
	public List<SearchResult> getResults() {
		return this.results;
	}
}
