/* ======================================================================
The Bodington System Software License, Version 1.0

Copyright (c) 2001 The University of Leeds.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1.  Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2.  Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3.  The end-user documentation included with the redistribution, if any,
must include the following acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
EVENT SHALL THE UNIVERSITY OF LEEDS OR ITS CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
=========================================================

This software was originally created by the University of Leeds and may contain voluntary
contributions from others.  For more information on the Bodington Open Source Project, please
see http://bodington.org/

====================================================================== */

package org.bodington.servlet.facilities;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.ServletException;

import org.apache.log4j.Logger;
import org.bodington.server.resources.Resource;
import org.bodington.servlet.HttpSession;
import org.bodington.servlet.Request;

/**
 * Facility class for methods relating to Search Tool web interface.
 * @author Colin Tatham
 */
public class SearchFacility extends Facility
{
    private static Logger log = Logger.getLogger(SearchFacility.class);
    
    /**
     * Allow search tool resources to be copied.
     * Even though it's unlikely to be required directly, it will 
     * allow resources containing search tools to be copied.
     * @param resource Resource intended for copying
     * @return true, indicating copying is allowed
     */
    public boolean canCopy( Resource resource )
    {
        return true;
    }
    
    public void insert( Request req, PrintWriter out, String command, String name )
    throws ServletException, IOException
    {
        Hashtable settings = getSearchSettings( req );
        Hashtable displayOptions = getDisplayOptions( req );
        
        if (command.equalsIgnoreCase("field"))
        {
            String[] fields = (String[])settings.get("fields");
            for ( int i = 0; i < fields.length; i++ )
            {
                if ( fields[i].equalsIgnoreCase( name ))
                    out.print("checked=\"checked\"");
            }                              
        }
        else if (command.equalsIgnoreCase("any_all_opt"))
        {
            if ( settings.get("any_all_opt").equals( name ) )
                out.print("selected=\"selected\"");                
        }
        else if (command.equalsIgnoreCase("search_terms"))
        {
            if ( settings.get("search_terms") != null )
                out.print( settings.get("search_terms") );                
        }
        else if (command.equalsIgnoreCase("general_strength"))
        {
            if ( settings.get("general_strength").equals( name ) )
                out.print("selected=\"selected\"");                              
        }
        
        // display option settings:
        else if (command.equalsIgnoreCase("displayDeleted"))
        {
            if ( displayOptions.get("displayDeleted") != null )
            {
                out.print("checked=\"checked\"");
            }
        }
        else if (command.equalsIgnoreCase("displayDescription"))
        {
            if ( displayOptions.get("displayDescription") != null )
            {
                out.print("checked=\"checked\"");
            }
        }
        else if (command.equalsIgnoreCase("displayKeywords"))
        {
            if ( displayOptions.get("displayKeywords") != null )
            {
                out.print("checked=\"checked\"");
            }
        }
        else if (command.equalsIgnoreCase("displayResourceType"))
        {
            if ( displayOptions.get( "displayResourceTypes" ) != null )
            {            
                if ( ((List)displayOptions.get( "displayResourceTypes" )).contains( name ))
                    out.print("selected=\"selected\"");
            }
        }
              
        else
            super.insert( req, out, command, name );
    }
    
    /**
     * Gets or updates a Hashtable of current search settings.
     * <br />Settings are stored in a session attribute.
     * @param req Request with current params for configuring search
     * @return Hashtable of settings
     */
    
    public static Hashtable getSearchSettings ( Request req )
    {
        HttpSession session;
        Hashtable settings;
        
        session = (HttpSession)req.getSession();
        settings = (Hashtable)session.getAttribute( "org.bodington.servlet.search_settings" );
        if ( settings == null )
            settings = setSearchDefaults( req );
        
        String search_terms = req.getParameter( "search_terms" );
        if ( search_terms != null )
            settings.put( "search_terms", search_terms );
        
        String[] fields = req.getParameterValues( "field" );
        if ( fields != null )
            settings.put( "fields", fields );
        
        String any_all_opt = req.getParameter( "any_all_opt" );
        if ( any_all_opt != null )
            settings.put( "any_all_opt", any_all_opt );
        
        String general_strength = req.getParameter( "general_strength" );
        if ( general_strength != null )
            settings.put( "general_strength", general_strength );
        
        session.setAttribute( "org.bodington.servlet.search_settings", settings );
        
        return settings;
    }
    
    /**
     * Gets or updates a Hashtable of options for displaying search results.
     * <br />Settings are stored in a session attribute.
     * @param req Request with current params for configuring display of results
     * @return Hashtable of settings
     */
    
    public static Hashtable getDisplayOptions ( Request req )
    {
        HttpSession session;
        Hashtable displayOptions;
        List included = new ArrayList();
        
        session = (HttpSession)req.getSession();
        displayOptions = (Hashtable)session.getAttribute( "org.bodington.servlet.search_display_options" );
        
        // no submit button pressed, but have options settings:
        if ( req.getParameter( "search" ) == null && displayOptions != null)
            return displayOptions;
        
        // no option settings available, use defaults:
        if ( displayOptions == null )
        {
            return setDisplayDefaults( req );
        }
        
        // otherwise update current saved settings:
        
        if ( req.getParameter("displayDeleted") != null )
            displayOptions.put("displayDeleted" , "");
        else
            displayOptions.remove("displayDeleted");
        
        if ( req.getParameter("displayDescription") != null )
            displayOptions.put("displayDescription", "");
        else
            displayOptions.remove("displayDescription");
        
        if ( req.getParameter("displayKeywords") != null )
            displayOptions.put("displayKeywords", "");
        else
            displayOptions.remove("displayKeywords");
        
        if ( req.getParameterValues("displayResourceType") != null )
        {
            // add the short names of any resource types that would normally be
            // excluded from the display of results, but that should be included:
            included = Arrays.asList(req.getParameterValues("displayResourceType"));            
        }
        
        displayOptions.put( "displayResourceTypes", included );
        
        session.setAttribute( "org.bodington.servlet.search_display_options", displayOptions );
        
        return displayOptions;
    }
    
    /**
     * Set default settings for search options.
     * <br />Settings are stored in a session attribute.
     * <br />Default settings:
     * <ul>
     * <li>Search term is an empty string</li>
     * <li>Title, description and keywords fields</li>
     * <li>Any (i.e OR) operator</li>
     * <li>Word strength match is Primary</li>
     * </ul>
     * @param req Request
     * @return Hashtable containing settings
     */
    private static Hashtable setSearchDefaults( Request req )
    {
        HttpSession session = (HttpSession)req.getSession( true );
        Hashtable settings = new Hashtable();
        
        settings.put( "search_terms", "" );
        
        String[] fields = new String[]{"title", "description", "keywords"};
        settings.put( "fields", fields );
        
        settings.put( "any_all_opt", "any" );
        settings.put( "general_strength", "primary" );
        
        session.setAttribute( "org.bodington.servlet.search_settings", settings );
        
        return settings;
    }
    
    /**
     * Set default settings for result display options.
     * <br />Settings are stored in a session attribute.
     * <br />Default settings:
     * <ul>
     * <li>Resource descriptions are displayed</li>
     * <li>Resource keywords are displayed if present</li>
     * </ul>
     * @param req Request
     * @return Hashtable containing settings
     */
    
    public static Hashtable setDisplayDefaults( Request req )
    {
        HttpSession session = (HttpSession)req.getSession( true );
        Hashtable displayOptions = new Hashtable();
        
        displayOptions.put("displayDescription", "");
        displayOptions.put("displayKeywords", "");
        
        session.setAttribute( "org.bodington.servlet.search_display_options", displayOptions );
        
        return displayOptions;
    }
    
    public boolean isSysadmin()
    {
        return true;
    }
}
