/*
 * 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.search.FilterSpecification;
import com.arsdigita.search.Search;
import com.arsdigita.search.ui.FilterWidget;
import com.arsdigita.search.filters.ObjectTypeFilterSpecification;
import com.arsdigita.search.filters.ObjectTypeFilterType;

import com.arsdigita.persistence.metadata.ObjectType;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.parameters.ArrayParameter;
import com.arsdigita.bebop.parameters.StringParameter;
import com.arsdigita.xml.Element;


/**
 * A filter component for presenting a list of object
 * types to select from.
 */
public class ObjectTypeFilterWidget extends FilterWidget {

    private ObjectType[] m_types;
    
    /**
     * Creates a new filter component for selecting amongst
     * a number of object types
     * @param types the types to select
     */
    public ObjectTypeFilterWidget(ObjectType[] types) {
        super(new ObjectTypeFilterType(),
              new ArrayParameter(new StringParameter(ObjectTypeFilterType.KEY)));

        m_types = types;
    }

    public FilterSpecification getFilter(PageState state) {
        String[] types = (String[])getValue(state);

        if (types == null) {
            types = new String[0];
        }

        return new ObjectTypeFilterSpecification(types);
    }
    
    public void generateBodyXML(PageState state,
                                Element parent) {
        super.generateBodyXML(state, parent);

        String[] types = (String[])getValue(state);

        for (int i = 0 ; i < m_types.length ; i++) {
            Element type = Search.newElement("objectType");
            type.addAttribute("name", m_types[i].getQualifiedName());
            for (int j = 0 ; j < types.length ; j++) {
                if (types[j].equals(m_types[i].getQualifiedName())) {
                    type.addAttribute("isSelected", "1");
                    break;
                }
            }
            parent.addContent(type);
        }
    }
}
