package org.seasar.jsf.util;

import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIComponent;
import javax.faces.component.ValueHolder;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.seasar.jsf.exception.NoValueHolderRuntimeException;

/**
 * @author higa
 *  
 */
public final class ValueHolderUtil {

	private ValueHolderUtil() {
	}
    
    public static Object getValue(UIComponent component) {
        if (!(component instanceof ValueHolder)) {
            throw new NoValueHolderRuntimeException(component.getClass());
        }
        ValueHolder vh = (ValueHolder) component;
        return vh.getValue();
    }

	public static String getValueAsString(FacesContext context,
			UIComponent component) {

		if (!(component instanceof ValueHolder)) {
			throw new NoValueHolderRuntimeException(component.getClass());
		}
		if (component instanceof EditableValueHolder) {
			EditableValueHolder evh = (EditableValueHolder) component;
			Object submittedValue = evh.getSubmittedValue();
			if (submittedValue != null) {
				if (submittedValue instanceof String) {
					return (String) submittedValue;
				}
				return submittedValue.toString();
			}
		}
		ValueHolder vh = (ValueHolder) component;
		Object value = vh.getValue();
		Converter converter = vh.getConverter();
		return UIValueUtil.getValueAsString(context, component, value, converter);
	}
}