package mildo.wiwo.search;

import java.util.HashMap;

import mildo.wiwo.data.WiwoPage;
import mildo.wiwo.persistence.PersistHelper;
import mildo.wiwo.search.dao.QuickSearch;

import com.webobjects.eocontrol.EOEditingContext;
import com.webobjects.eocontrol.EOQualifier;
import com.webobjects.foundation.NSArray;
import com.webobjects.foundation.NSMutableArray;

public class SearchHelper {

	public SearchHelper(PersistHelper aHelper) {
		persistHelper = aHelper;
	}
	
	private PersistHelper persistHelper;
	
	public NSArray primitiveSearch(String aSearchValue) {
		NSArray ret = WiwoPage.fetchWiwoPages(persistHelper.editingContext(), 
				EOQualifier.qualifierWithQualifierFormat("name = '" + aSearchValue + "'", null), null);
		return ret;
	}
	
	public NSArray quickSearch(QuickSearch aValue) {
		NSMutableArray ret = new NSMutableArray();
		HashMap theMap = new HashMap();
		if (aValue != null && aValue.getName() != null && aValue.getName().length() > 0) {
			ret = persistHelper.fetchPages4Name(aValue.getName(), aValue.getSorts()).mutableClone();
		}
		for (int i = ret.count() - 1; i >= 0; i--) {
			WiwoPage thePage = (WiwoPage) ret.objectAtIndex(i);
			if (!theMap.containsKey(thePage.name())) {
				theMap.put(thePage.name(), thePage);
			}
		}
		ret = new NSMutableArray();
		ret.addAll(theMap.values());
		return ret.immutableClone();
	}
	
}
