/*
 * Copyright (C) 2003-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.cms.ui.category;

import com.arsdigita.bebop.list.ListModel;
import com.arsdigita.categorization.Category;
import com.arsdigita.categorization.CategoryCollection;

import java.math.BigDecimal;

/**
 * A {@link ListModel} that iterates over categories via a cursor.
 */
public final class CategoryCollectionListModel implements ListModel {

    private Category m_cat;
    private BigDecimal m_excludedID;
    private CategoryCollection m_categories;


    /**
     * Constructs a new <code>CategoryCollectionListModel</code>
     */
    public CategoryCollectionListModel(CategoryCollection coll) {
        this(coll, null);
    }

    /**
     * Constructs a new <code>CategoryCollectionListModel</code>
     */
    public CategoryCollectionListModel(CategoryCollection coll,
                                       BigDecimal excludedID) {

        m_categories = coll;
        m_excludedID = excludedID;
        m_cat = null;
    }

    public boolean next() {
        if ( m_categories.next() ) {
            final Category category = m_categories.getCategory();
            if ( category.getID().equals(m_excludedID) ) {
                return next();
            } else {
                m_cat = category;
                return true;
            }
        } else {
            return false;
        }
    }

    private Category getCategory() {
        if ( m_cat == null ) {
            throw new IllegalStateException("call next() first");
        }
        return m_cat;
    }

    public Object getElement() {
        return getCategory().getName();
    }

    public String getKey() {
        return getCategory().getID().toString();
    }
}
