/*
 * Copyright (C) 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.ui.FilterWidget;
import com.arsdigita.search.Search;
import com.arsdigita.search.FilterSpecification;
import com.arsdigita.search.FilterType;
import com.arsdigita.kernel.Party;
import com.arsdigita.kernel.PartyCollection;
import com.arsdigita.xml.Element;
import com.arsdigita.bebop.parameters.StringParameter;
import com.arsdigita.bebop.PageState;
import com.arsdigita.search.filters.PartyFilterSpecification;
import com.arsdigita.util.StringUtils;


/**
 *  This is a base widget that can be used to restrict a search
 *  to a certain group of users.
 */
public class PartyFilterWidget extends FilterWidget {

    public final static String PARTY_TEXT = "partyText";

    private FilterType m_type;
    private String m_paramName;

    /**
     *  This creates a text field that can be used to restrict
     *  the results by user.  The passed in is used for the parameter
     *  that holds the user input party informaiton
     */
    public PartyFilterWidget(FilterType type, String parameterName) {
        super(type, new StringParameter(parameterName));
        m_type = type;
        m_paramName = parameterName;
    }
    
    public FilterSpecification getFilter(PageState state) {
        String searchTerm = (String)getValue(state);
        if (searchTerm == null || searchTerm.trim().length() == 0) {
            return new PartyFilterSpecification(null,
                                                m_type);
        } else {
            return new PartyFilterSpecification(getParties(searchTerm),
                                                m_type);
        }
    }

    private PartyCollection getParties(String searchTerm) {
        searchTerm = StringUtils.stripWhiteSpace(searchTerm);
        PartyCollection parties = Party.retrieveAllParties();
        parties.filter(searchTerm);
        return parties;
    }

    public void generateBodyXML(PageState state,
                                Element parent) {
        super.generateBodyXML(state, parent);
        
        Element partyElement = Search.newElement(PARTY_TEXT);
        partyElement.addAttribute("name", m_paramName);
        partyElement.addAttribute("value", (String)getValue(state));
        parent.addContent(partyElement);
        
    }
}
