/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

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

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;
    }
}
