/*
 * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.toolbox.ui;



import java.util.Iterator;
import com.arsdigita.bebop.list.ListModel;




/**
 * <p>Simple adapter to build a Bebop ListModel from a Java Iterator.</p>
 **/
public class IteratorListModel implements ListModel {

    /**
     * <p>An instance of this interface may be passed to
     * IteratorListModel's constructor for those situations where
     * element.toString() does not produce an appropriate key for a
     * ListModel.</p>
     **/
    public static interface KeyFunction {
        public String getKey(Object object);
    }

    Iterator m_iterator;
    KeyFunction m_keyFunction;
    Object m_current;

    public IteratorListModel(Iterator iterator,
                             KeyFunction keyFunction) {
        m_iterator = iterator;
        m_keyFunction = keyFunction;
    }

    public IteratorListModel(Iterator iterator) {
        this(iterator, null);
    }

    public Object getElement() {
        return m_current;
    }

    public String getKey() {
        if (m_keyFunction != null) {
            return m_keyFunction.getKey(m_current);
        } else {
            return m_current.toString();
        }
    }

    public boolean next() {
        if (!m_iterator.hasNext()) {
            return false;
        }
        m_current = m_iterator.next();
        return true;
    }
}
