package com.sophora.processing.extension;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import org.apache.tapestry.form.IPropertySelectionModel;
import org.objectstyle.cayenne.CayenneDataObject;

/**
 * Generic selection model that works with lists of CayenneDataObjects,
 * provided that a label value is the property of the object. Overriding
 * "getLabel" will allow to customize it further.
 * 
 *..uthor Eric Schneider
 */
public class DataObjectSelectionModel implements IPropertySelectionModel, Serializable {
    protected String noSelectionLabel;
    protected List dataObjects;
    protected String labelKey;

    public DataObjectSelectionModel() {
    }
    
    public DataObjectSelectionModel(List dataObjects, String labelKey) {
        this(dataObjects, labelKey, null);
    }

    public DataObjectSelectionModel(
        List dataObjects,
        String labelKey,
        String noSelectionLabel) {

        this.noSelectionLabel = noSelectionLabel;
        this.dataObjects = dataObjects;
        this.labelKey = labelKey;
    }

    public int getOptionCount() {
        int size = dataObjects.size();
        return (noSelectionLabel != null) ? size + 1 : size;
    }

    public Object getOption(int index) {
        if (noSelectionLabel != null) {
            if (index == 0) {
                return null;
            }

            index--;
        }

        return dataObjects.get(index);
    }

    public String getLabel(int index) {
        Object obj = getOption(index);
        if (obj == null) {
            return noSelectionLabel;
        }

        return String.valueOf(
            ((CayenneDataObject) obj).readNestedProperty(labelKey));
    }

    public String getValue(int index) {
        return Integer.toString(index);
    }

    public Object translateValue(String value) {
        return getOption(Integer.parseInt(value));
    }
	/**
	 *..eturn List
	 */
	public Iterator getModelIterator() {
		return dataObjects.iterator();
	}

}

