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



import java.util.Iterator;
import com.arsdigita.persistence.Session;
import com.arsdigita.persistence.DataQuery;
import com.arsdigita.persistence.SessionManager;
import com.arsdigita.persistence.OID;
import java.math.BigDecimal;
import com.arsdigita.kernel.permissions.PermissionService;
import com.arsdigita.kernel.permissions.PrivilegeDescriptor;

/**
 * 
 * This class iterates through the query, setting up the correct values
 * for the tree node
 *
 * @author Daniel Berrange 
 * @author Randy Graebner
 *
 * @version $Id: //core-platform/dev/src/com/arsdigita/kernel/ui/DataQueryTreeIterator.java#6 $
 */
public class DataQueryTreeIterator implements Iterator  {
    protected DataQuery m_nodes;
    
    public DataQueryTreeIterator(DataQueryTreeNode node, 
                                 String getSubCategories) {
        Session session = SessionManager.getSession();
        m_nodes = session.retrieveQuery(getSubCategories);
        m_nodes.setParameter("objectID", node.getID());
    }

    public void filterQuery(String propertyName,
                            PrivilegeDescriptor privilege,
                            OID userOID) {
        PermissionService.filterQuery(m_nodes, propertyName, privilege, userOID);
    }

    /**
     *  This allows the calling class to use data queries that
     *  need extra variables set.  This is used by FolderTreeModelBuilder
     *  in CMS but is generally useful so it has been added here.
     */
    public void setParameter(String parameterName, Object parameterValue) {
        m_nodes.setParameter(parameterName, parameterValue);
    }

    /**
     *  This allows the calling class to order the results of the data query
     */
    public void addOrder(String parameterName) {
        m_nodes.addOrder(parameterName);
    }

    public Object next() {
        BigDecimal id = (BigDecimal)m_nodes.get("id");
        String name = (String)m_nodes.get("name");
        BigDecimal count = (BigDecimal)m_nodes.get("nchild");
        
        return new DataQueryTreeNode(id, name, count.intValue() > 0);
    }
    
    public void remove() {
        throw new UnsupportedOperationException
            ("cannot remove categories via iterator");
    }
    
    public boolean hasNext() {
        return m_nodes.next();
    }
}
