package inc.monsters.mias.conversion;

import inc.monsters.mias.data.FoodList;

import java.util.Collection;

import javax.faces.component.StateHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.myfaces.trinidad.convert.ClientConverter;

public class FoodListConverter implements Converter, ClientConverter, StateHolder {
	private String separator = " ";

	public Object getAsObject(FacesContext context, UIComponent component, String string) {
		String[] list = string.split(getSeparator());
		FoodList foodList = new FoodList();
		for(String food : list) {
			foodList.add(food);
		}
		return foodList;
	}

	public String getAsString(FacesContext context, UIComponent component, Object foodList) {
		if(foodList != null) {
			return ((FoodList)foodList).toStringWithSeparator(getSeparator());
		} else {
			return "";
		}
	}

	public String getSeparator() {
		return separator;
	}

	public void setSeparator(String separator) {
		this.separator = separator;
	}

	public String getClientConversion(FacesContext context, UIComponent component) {
		return "new FoodListConverter('"+getSeparator()+"');";
	}

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

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

	public String getClientScript(FacesContext context, UIComponent arg1component) {
		return null;
	}
	
	// The next four methods implement the StateHolder interface
	public boolean isTransient() {
		return false;
	}

	public void restoreState(FacesContext context, Object object) {
		this.separator = (String) object;
		
	}

	public Object saveState(FacesContext context) {
		return separator;
	}

	public void setTransient(boolean arg0) {
	}
}
