package inc.monsters.mias.conversion;

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

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

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

public class CaseConverter implements Converter, ClientConverter, StateHolder {
	private static final Logger log = Logger.getLogger("inc.monsters.mias");
	private String type = "lower";
	
	public CaseConverter() {
		log.fine("CaseConverter constructor called.");
	}
	
	public Object getAsObject(FacesContext context, UIComponent component, String string) {
		log.fine("getAsObject(" + string + "), type = " + type);
		String result = "";
		if ("upper".equals(type)){
			result = string.toUpperCase();
		} else if ("title".equals(type)) {
			result = toTitleCase(string);
	    } else {
			result = string.toLowerCase();
		}
		log.fine("result (" + type + "): " + result);
		return result;
	}
	
	private String toTitleCase(String string){
		StringBuilder sb = new StringBuilder();     
		String lower = string.toLowerCase();
		
		// Split the input string at every whitespace character (\s)
		String[] words = lower.split("\\s");
		
		for(String word : words) {
			sb.append(" ");
			sb.append(word.replaceFirst(word.substring(0,1),word.substring(0,1).toUpperCase()));
		}
		
		String result = sb.toString();
		log.finer("toTitleCase(" + string + ") --> " + result + ".");
		return result.substring(1); // remove the first space
	}

	public String getAsString(FacesContext context, UIComponent component, Object object) {
		context.getExternalContext().getSessionMap().put(component.getId()+"CaseConverterType", getType());
		log.fine("getAsString(" + object.toString() + ")");
		return object.toString();
	}

	/**
	 * @param type the type to set
	 */
	public void setType(String type) {
		log.fine("setType(" + type + ")");
		if (type != null) {
			this.type = type.toLowerCase(); 
		}
	}

	public String getType() {
		return type;
	}

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

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

	public String getClientLibrarySource(FacesContext context) {
		return context.getExternalContext().getRequestContextPath() + "/scripts/CaseConverter.js";    
	}

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

	// The next four methods implement the StateHolder interface
	public boolean isTransient() {
		return false;
	}

	public void setTransient(boolean b) {
	}

	public void restoreState(FacesContext context, Object object) {
		type = (String) object;
	}

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


}
