/*
 *    AbstractTextSearch.java
 *    Copyright (C) 2005 New Zealand Digital Library, http://www.nzdl.org
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package org.greenstone.gsdl3.service;

// Greenstone classes
import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.greenstone.gsdl3.util.GSXML;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Partially implements a generic text based search service. TextQuery and QuickQuery
 * 
 */

public abstract class AbstractTextSearch extends AbstractSearch
{

  static Logger logger = Logger.getLogger(org.greenstone.gsdl3.service.AbstractTextSearch.class.getName());
  public static final String TEXT_QUERY_SERVICE = "TextQuery";
  // the quick search service - piggybacks onto the other one
  public static final String QUICK_QUERY_SERVICE =  "QuickQuery";

    // search types in <search> element in collectionCOnfig
  	protected static final String SEARCH_TYPE_ELEM = "searchType";
        protected static final String SEARCH_TYPE_QUICK = "quick";
	protected static final String SEARCH_TYPE_PLAIN = "plain";

 	// which search services will we offer??
        protected boolean quick_search = false;
	protected boolean plain_search = false;

  // optional standard params - some of these have to be implemented
	protected static final String INDEX_SUBCOLLECTION_PARAM = "indexSubcollection";
	protected static final String INDEX_LANGUAGE_PARAM = "indexLanguage";

	protected static final String INDEX_SUBCOLLECTION_ELEM = "indexSubcollection";
	protected static final String INDEX_LANGUAGE_ELEM = "indexLanguage";

	// some other common params that may be used
	protected static final String CASE_PARAM = "case";
	protected static final String STEM_PARAM = "stem";
	protected static final String ACCENT_PARAM = "accent";

	protected static final String BOOLEAN_PARAM_ON = "1";
	protected static final String BOOLEAN_PARAM_OFF = "0";
	protected static final String MATCH_PARAM = "matchMode";
	protected static final String MATCH_PARAM_ALL = "all";
	protected static final String MATCH_PARAM_SOME = "some";

	protected String default_index_subcollection = "";

	protected String default_index_language = "";

	public AbstractTextSearch()
	{
	  super();
		// the search service
		QUERY_SERVICE = TEXT_QUERY_SERVICE;
		paramDefaults.put(CASE_PARAM, BOOLEAN_PARAM_ON);
		paramDefaults.put(STEM_PARAM, BOOLEAN_PARAM_OFF);
		paramDefaults.put(ACCENT_PARAM, BOOLEAN_PARAM_ON);
		paramDefaults.put(MATCH_PARAM, MATCH_PARAM_SOME);
	}

  	public boolean configure(Element info, Element extra_info)
	{
		if (!super.configure(info, extra_info))
		{
			return false;
		}

		logger.info("Configuring AbstractTextSearch...");
		// we need to set up the save_params - we want all our search settings saved by default
		this.save_params.add(INDEX_SUBCOLLECTION_PARAM);
		this.save_params.add(INDEX_LANGUAGE_PARAM);
		this.save_params.add(CASE_PARAM);
		this.save_params.add(STEM_PARAM);
		this.save_params.add(ACCENT_PARAM);
		this.save_params.add(MATCH_PARAM);

                // load up any search types
		Element search_elem = (Element) GSXML.getChildByTagName(extra_info, GSXML.SEARCH_ELEM);
		if (search_elem != null) {
                  getSearchTypes(search_elem);
                }

                // set up short_service_info based on search types 
		// => for now just has id and type. the name (lang dependent)
		//    will be added in if the list is requested.
                if (this.quick_search) {

                  Element qs_service = this.desc_doc.createElement(GSXML.SERVICE_ELEM);
                  qs_service.setAttribute(GSXML.TYPE_ATT, GSXML.SERVICE_TYPE_QUERY);
                  qs_service.setAttribute(GSXML.NAME_ATT, QUICK_QUERY_SERVICE);
                  this.short_service_info.appendChild(qs_service);

                }

                if (!this.plain_search) {
                  //plain search would have been added by AbstractSearch
                  // so remove it
                  
                  Element tq_service = GSXML.getNamedElement(short_service_info, GSXML.SERVICE_ELEM, GSXML.NAME_ATT, TEXT_QUERY_SERVICE);
                  short_service_info.removeChild(tq_service);
                  
                }

                // copy any format info into quick search
                Node format = this.format_info_map.get(TEXT_QUERY_SERVICE);
                if (format != null) {
                  
                  this.format_info_map.put(QUICK_QUERY_SERVICE, format);
                }
		return true;

                  
                                  
	}

  protected void getSearchTypes(Element search_elem) {
    NodeList search_types = search_elem.getElementsByTagName(SEARCH_TYPE_ELEM);
    if (search_types == null)
    {
      // none specified, old style, assume plain and quick both enabled
      this.plain_search = true;
      this.quick_search = true;
      return;
    }
    
    boolean found_quick_search = false;
    for (int i = 0; i < search_types.getLength(); i++)
    {
      Element t = (Element) search_types.item(i);
      
      String type_name = t.getAttribute(GSXML.NAME_ATT);
      boolean enabled = true; // old style - no disabled attribute, 
      String disabled_str = t.getAttribute(GSXML.DISABLED_ATT);
      if (disabled_str.equals("true")) {
        // we have specifically disabled this search type
        enabled = false;
      }
      // else either disabled = false, or there is no disabled att => enabled stays true
      if (type_name.equals(SEARCH_TYPE_QUICK)) {
        // this wasn;t there before, so we need to know if it is there now
        found_quick_search = true;
        if (enabled) {
          this.quick_search = true;
        }
      }
      else if (type_name.equals(SEARCH_TYPE_PLAIN)) {
        if (enabled) {
          this.plain_search = true;
        }
      }
      else {
        saveCustomSearchType(type_name, enabled);
      }
    } // foreach searchtype
    
    if (!found_quick_search && this.plain_search) {
      // old style - no quick search specified, its available if plain search is available
      this.quick_search = true;
    }
  }

  // default is to do nothing. subclasses to handle their new searchtypes
  protected void saveCustomSearchType(String type_name, boolean enabled){};


  /** adds a couple extra params into the service description */
  protected void addQueryParams(String service_id, Element param_list, String lang)
	{
          // these go first
		if (!default_index_subcollection.equals(""))
		{
			createParameter(INDEX_SUBCOLLECTION_PARAM, param_list, lang);
		}
		if (!default_index_language.equals(""))
		{
			createParameter(INDEX_LANGUAGE_PARAM, param_list, lang);
		}
                // then AbstractSearch's standard ones come next
		super.addQueryParams(service_id, param_list, lang);
	}

	/**
	 * Top up createParameterChain with TextQuery specific params: case, stem
	 * ...
	 */
	protected boolean createParameterChain(String name, Element param_list, String lang, String default_value)
	{
	  Document doc = param_list.getOwnerDocument();
		Element param = null;
		String param_default = default_value;
		if (default_value == null) {
		  // have we got a stored up default? will be null if not there
		  param_default = paramDefaults.get(name);
		}

		if (super.createParameterChain(name, param_list, lang, default_value))
		{
			// found a match, so can stop here
			return true;
		}
		// otherwise look to see if it is a text specific parameter
		if (name.equals(INDEX_SUBCOLLECTION_PARAM))
		{
			Element index_sub_list = (Element) GSXML.getChildByTagName(this.config_info, INDEX_SUBCOLLECTION_ELEM + GSXML.LIST_MODIFIER);
			if (index_sub_list == null)
				return true; // processed, just not a very interesting result
			ArrayList<String> index_sub_ids = new ArrayList<String>();
			ArrayList<String> index_sub_names = new ArrayList<String>();
			getIndexSubcollectionData(index_sub_ids, index_sub_names, lang);
			String param_type = GSXML.PARAM_TYPE_ENUM_SINGLE;
			if (does_multi_index_search)
			{
				param_type = GSXML.PARAM_TYPE_ENUM_MULTI;
			}
			if (param_default == null)
			{
				param_default = this.default_index_subcollection;
			}
			param = GSXML.createParameterDescription2(doc, INDEX_SUBCOLLECTION_PARAM, getTextString("param." + INDEX_SUBCOLLECTION_PARAM, lang), param_type, param_default, index_sub_ids, index_sub_names);
			param_list.appendChild(param);
			return true;
		}
		else if (name.equals(INDEX_LANGUAGE_PARAM))
		{
			Element index_lang_list = (Element) GSXML.getChildByTagName(this.config_info, INDEX_LANGUAGE_ELEM + GSXML.LIST_MODIFIER);
			if (index_lang_list == null)
				return true; // processed, just not a very interesting result
			ArrayList<String> index_lang_ids = new ArrayList<String>();
			ArrayList<String> index_lang_names = new ArrayList<String>();
			getIndexLanguageData(index_lang_ids, index_lang_names, lang);
			String param_type = GSXML.PARAM_TYPE_ENUM_SINGLE;
			if (does_multi_index_search)
			{
				param_type = GSXML.PARAM_TYPE_ENUM_MULTI;
			}
			if (param_default == null)
			{
				param_default = this.default_index_language;
			}
			param = GSXML.createParameterDescription2(doc, INDEX_LANGUAGE_PARAM, getTextString("param." + INDEX_LANGUAGE_PARAM, lang), param_type, param_default, index_lang_ids, index_lang_names);
			param_list.appendChild(param);
			return true;
		}
	else if (name.equals(CASE_PARAM) || name.equals(STEM_PARAM) || name.equals(ACCENT_PARAM)) {
	    String[] bool_ops = {"0", "1"};
	    String[] bool_texts = {getTextString("param.boolean.off", lang),getTextString("param.boolean.on", lang)}; 
	    param = GSXML.createParameterDescription(doc, name, getTextString("param."+name, lang), GSXML.PARAM_TYPE_BOOLEAN, param_default, bool_ops, bool_texts);
	    param_list.appendChild(param);
	    return true;
	} else if (name.equals(MATCH_PARAM)) {
	  
	    String[] vals = {MATCH_PARAM_SOME, MATCH_PARAM_ALL };
	    String[] val_texts = {getTextString("param."+MATCH_PARAM+"."+MATCH_PARAM_SOME, lang), getTextString("param."+MATCH_PARAM+"."+MATCH_PARAM_ALL, lang)}; 
	    param = GSXML.createParameterDescription(doc, MATCH_PARAM, getTextString("param."+MATCH_PARAM, lang), GSXML.PARAM_TYPE_ENUM_SINGLE, param_default, vals, val_texts);
	    param_list.appendChild(param);
	    return true;
	}
		// Get to here then none of the above params matched
		// => return false so the chain can continue
		return false;

	}


  
  /** for quick search, we just pass to textquery */
  protected Element processQuickQuery(Element request) {
    return processAnyQuery(request, QUICK_QUERY_SERVICE);
  }

    protected Element processTextQuery (Element request) {
      return processAnyQuery(request, TEXT_QUERY_SERVICE);
    }

 	/**
	 * do the actual query must be implemented by subclass
	 */
  abstract protected Element processAnyQuery(Element request, String service_name);

	/**
	 * get the details about the indexexSubcollections available might be
	 * implemented by subclass
	 */
	protected void getIndexSubcollectionData(ArrayList<String> index_ids, ArrayList<String> index_names, String lang)
	{
	}

	/**
	 * get the details about the indexes available might be implemented by
	 * subclass
	 */
	protected void getIndexLanguageData(ArrayList<String> index_ids, ArrayList<String> index_names, String lang)
	{
	}

}
