/*
 * 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.search.ui.filters;

import com.arsdigita.categorization.Category;
import com.arsdigita.categorization.CategoryCollection;
import com.arsdigita.bebop.PageState;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;

/**
 * A simple category filter which displays all
 * subcategories from a specified root
 */
public class SimpleCategoryFilterWidget extends CategoryFilterWidget {
    
    private static final Logger s_log =
        Logger.getLogger(SimpleCategoryFilterWidget.class);

    private Category[] m_roots;
    
    /**
     * Creates a new category filter
     * @param root the root category
     */
    public SimpleCategoryFilterWidget(Category root) {
        this(new Category[] { root });
    }

    /**
     * Creates a new category filter
     * @param root the list of root categories
     */
    public SimpleCategoryFilterWidget(Category[] roots) {
        m_roots = roots;
    }


    public Category[] getCategories(PageState state) {
        s_log.info("getCategories", new Throwable());
        Collection cats = new ArrayList();
        Set seen = new HashSet();
        for (int i = 0 ; i < m_roots.length ; i++) {
            if (seen.contains(m_roots[i])) {
                if (s_log.isDebugEnabled()) {
                    s_log.debug("skipping category " + m_roots[i].getOID());
                }
                continue;
            }

            if (s_log.isDebugEnabled()) {
                s_log.debug("processing category " + m_roots[i].getOID());
            }

            CategoryCollection scions = m_roots[i].getDescendants();
            while ( scions.next() ) {
                cats.add(scions.getCategory());
            }
            scions.close();
            seen.add(m_roots[i]);
        }
        return (Category[])cats.toArray(new Category[cats.size()]);
    }

}
