package org.inria.bmajwatcher.client.ui.bank_editor;

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


import com.google.gwt.user.client.ui.SuggestOracle;


/**
 * 
 * Custom suggestion oracle used for suggest box.
 * 
 * @author rsabas
 *
 */
public class MySuggestOracle extends SuggestOracle {
	
	private Collection<String> processes;
	
	public MySuggestOracle(Collection<String> ps) {
		processes = ps;
	}
	
	public class MySuggestion implements Suggestion {
		
		private String _value;
		private String _query;
		
		public MySuggestion(String value, String query) {
			_value = value;
			_query = query;
		}
		
		@Override
		public String getDisplayString() {
			if (_query.equals("*"))
				return _value;
			
			return _value.replaceFirst(_query, "<b>" + _query + "</b>");
		}

		@Override
		public String getReplacementString() {
			return _value;
		}
		
	}

	@Override
	public void requestSuggestions(Request request, Callback callback) {
		final List<MySuggestion> suggestions = getSuggestions(request.getQuery().toLowerCase());
		Response response = new Response(suggestions);
		callback.onSuggestionsReady(request, response);
	}
	
	/**
	 * Determines what processes should be displayed.
	 * 
	 * @param req
	 * 
	 * @return
	 */
	private List<MySuggestion> getSuggestions(String req) {
		List<MySuggestion> res = new ArrayList<MySuggestion>();
		for (String s : processes) {
			if (req.equals("*")) {
				res.add(new MySuggestion(s, req));
			} else if (s.contains(req)) {
				res.add(new MySuggestion(s, req));
			}
		}
		
		return res;
	}
	
	@Override
	public boolean isDisplayStringHTML() {
		return true;
	}
}
