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


import com.arsdigita.search.ui.FilterWidget;
import com.arsdigita.search.Search;
import com.arsdigita.search.FilterSpecification;
import com.arsdigita.cms.ContentType;
import com.arsdigita.cms.ContentTypeCollection;
import com.arsdigita.cms.ContentSection;
import com.arsdigita.xml.Element;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.parameters.ArrayParameter;
import com.arsdigita.bebop.parameters.StringParameter;
import com.arsdigita.cms.search.ContentTypeFilterType;
import com.arsdigita.cms.search.ContentTypeFilterSpecification;

public class ContentTypeFilterWidget extends FilterWidget {

    private ContentType[] m_types;
    
    public ContentTypeFilterWidget(ContentTypeCollection types) {
        super(new ContentTypeFilterType(),
              new ArrayParameter(new StringParameter(ContentTypeFilterType.KEY)));

        m_types = new ContentType[(int)types.size()];
        int i = 0;
        while (types.next()) {
            m_types[i++] = types.getContentType();
        }
    }
    public ContentTypeFilterWidget(ContentSection section) {
        this(section.getContentTypes());
    }

    public ContentTypeFilterWidget() {
        this(ContentType.getRegisteredContentTypes());
    }
    
    public FilterSpecification getFilter(PageState state) {
        String[] types = (String[])getValue(state);
        
        if (types == null) {
            types = new String[0];
        }
        
        return new ContentTypeFilterSpecification(types);
    }
    
    public void generateBodyXML(PageState state,
                                Element parent) {
        super.generateBodyXML(state, parent);

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

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



            parent.addContent(type);
        }
    }
}
