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

import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.SimpleContainer;

import com.arsdigita.search.QuerySpecification;
import com.arsdigita.search.FilterSpecification;
import com.arsdigita.search.Search;
import com.arsdigita.util.Assert;


/**
 * A base class for generating a query specification
 * from the state. Subclasses must implement two
 * methods, one for getting the query tmers,
 * the other for gettting a set of filter specs.
 */
public abstract class QueryComponent extends SimpleContainer 
    implements QueryGenerator {
    
    public QueryComponent(String name) {
        setTag(Search.XML_PREFIX + name);
        setNamespace(Search.XML_NS);
    }
    
    /**
     * Determine if a query specification is available
     * @return true if the user has entered some search terms
     */
    public boolean hasQuery(PageState state) {
        String terms = getTerms(state);

        return (terms != null &&
                !"".equals(terms));
    }
    
    /**
     * Returns the current query specification
     */
    public QuerySpecification getQuerySpecification(PageState state) {
        Assert.truth(hasQuery(state));

        String terms = getTerms(state);
        
        FilterSpecification[] filters = getFilters(state);
        
        if (filters == null) {
            return new QuerySpecification(terms, true);
        } else {
            return new QuerySpecification(terms, true, filters);
        }
    }
    
    /**
     * Returns the current query terms
     * @return the query terms, or null
     */
    protected abstract String getTerms(PageState state);
    
    /**
     * Returns the current filter specifications
     * @return the list of filter specs
     */
    protected abstract FilterSpecification[] getFilters(PageState state);
}
