package inc.monsters.mias.validators;

import java.util.Collection;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Logger;

import inc.monsters.mias.data.FoodList;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.apache.myfaces.trinidad.validator.ClientValidator;

import com.sun.xml.ws.mex.client.schema.GetMetadata;

public class FoodListValidator implements Validator, ClientValidator {
	private static final Logger log = Logger.getLogger("inc.monsters.mias");

	public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
		int errors = 0;
		StringBuilder wrong = new StringBuilder();
		for (String food : ((FoodList) value).getAsList()) {
			if (!food.matches("[A-Za-z]*")) {
				if (errors > 0) {
					wrong.append(" ");
				}
				wrong.append(food);
				errors++;
			}
		}

		if (errors > 0) {
			FacesMessage msg = new FacesMessage();
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			msg.setSummary("Validation Error");
			msg.setDetail(wrong.toString() + (errors == 1 ? " is not a valid food name" : " are not valid food names"));
			throw new ValidatorException(msg);
		}
	}

	public Collection<String> getClientImportNames() {
		return null;
	}

	public String getClientLibrarySource(FacesContext context) {
		ExternalContext ec = context.getExternalContext();
		return ec.getRequestContextPath() + "/scripts/FoodListValidator.js";    
	}

	public String getClientScript(FacesContext context, UIComponent component) {
		return null;
	}

	public String getClientValidation(FacesContext context, UIComponent component) {
		String bundle = context.getApplication().getMessageBundle();
		log.fine("Message bundle: " + bundle);
		Locale locale = context.getViewRoot().getLocale();
		log.fine("Locale: " + locale);
		ResourceBundle msg = ResourceBundle.getBundle(bundle, locale);
		log.fine("Resource bundle: " + msg);
		return "new FoodListValidator(\"" + msg.getString("NoValidFoodErrorTitle")+ "\", \"" + msg.getString("NoValidFoodError") + "\");";
	}
}
