package org.seasar.jsf.util;

import java.lang.reflect.Array;
import java.util.List;

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

import org.seasar.framework.log.Logger;

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

    private static Logger logger = Logger.getLogger(UIValueUtil.class);

    private UIValueUtil() {
    }

    public static final boolean isEmpty(Object value) {
        return value == null || "".equals(value);
    }

    public static final boolean isManyEmpty(Object value) {
        return value == null
                || (value.getClass().isArray() && Array.getLength(value) == 0)
                || ((value instanceof List) && ((List) value).isEmpty());
    }

    public static String getValueAsString(FacesContext context,
            UIComponent component, Object value, Converter converter) {

        if (converter == null && value != null) {
            if (value instanceof String) {
                return (String) value;
            }
            try {
                converter = context.getApplication().createConverter(
                        value.getClass());
            } catch (FacesException ex) {
                logger.log(ex);
            }
        }
        if (converter == null) {
            if (value == null) {
                return "";
            }
            return value.toString();
        }
        return converter.getAsString(context, component, value);
    }
}