package org.apache.xindice.server.rpc.messages;

/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  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 acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xindice" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION 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 consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999-2001, The dbXML
 * Group, L.L.C., http://www.dbxmlgroup.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * $Id: Query.java,v 1.2 2002/10/31 07:00:44 vladimir Exp $
 */

import org.apache.xindice.core.Collection;
import org.apache.xindice.core.data.DocumentSet;
import org.apache.xindice.core.Container;

import org.apache.xindice.server.rpc.RPCDefaultMessage;
import org.apache.xindice.server.rpc.messages.Query;

import org.apache.xindice.xml.TextWriter;
import org.apache.xindice.xml.dom.DocumentImpl;


import org.apache.oro.text.perl.*;
import org.apache.oro.text.regex.*;

import org.w3c.dom.*;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;

/**
 * Executes a grep against all the documents in a collection
 * @return The result of the query as XML.
 */

public class Grep extends Query {

	// this is the length of the prefix and postfix matches returned.
	private static final int SUBSTRING_LENGTH = 40;

	public Hashtable execute(Hashtable message) throws Exception {

		if(!message.containsKey(COLLECTION)) {
		    throw new Exception(MISSING_COLLECTION_PARAM);
		}

		if(!message.containsKey(TYPE)) {
		    throw new Exception(MISSING_TYPE_PARAM);
		}

		if(!message.containsKey(QUERY)) {
		    throw new Exception(MISSING_QUERY_PARAM);
		}

		String collname = (String)message.get(COLLECTION);
		Collection col = getCollection( collname );

		String regex = prepareRegex((String)message.get(QUERY));

		// now fetch the document set from this collection
		DocumentSet doc_set = col.getDocumentSet();

		Document doc = findMatches(doc_set,regex,collname);

		Hashtable result = new Hashtable();
		result.put(RESULT, TextWriter.toString( doc ));
		return result;
	}

   /**
    * actually perform the grep against all the documents in this collection
	*
	* @param ds DocumentSet
	* @param regex String the perl-friendly regex
	* @param collectionName String the name of this collection
	* @return Document an XML document with all the matches.
    */
	private Document findMatches(DocumentSet ds, String regex, String collectionName)
                            throws Exception
    {

		DocumentImpl doc = new DocumentImpl();
        Element root = doc.createElement( "results" );
        doc.appendChild( root );
        int matchcount = 0;
        int doccount = 0;
        Perl5Util util = new Perl5Util();

        // now find all the matches
        while(ds.hasMoreDocuments())
        {
            Container container = ds.getNextContainer();
            // stringify the document, and run it against the regex
            Document doctmp = container.getDocument();
            String docStr = TextWriter.toString(doctmp);
            //org.apache.xindice.Debug.println("looking at next doc "+
            //                  container.getKey().toString());
            PatternMatcherInput input = new PatternMatcherInput(docStr);

            boolean firstTime = true;
            Element outputElement = null;
            MatchResult matchResult = null;
            while(util.match(regex,input))
            {
                //org.apache.xindice.Debug.println("matched "+util.group(0));
                // now add a node to our document!
                if(firstTime)
                {
                    outputElement = doc.createElement("matchdoc");
				    outputElement.setAttribute("xmlns:src", "http://xml.apache.org/xindice/Query");
                    outputElement.setAttributeNS("http://xml.apache.org/xindice/Query", "src:key", container.getKey().toString());
                    outputElement.setAttributeNS("http://xml.apache.org/xindice/Query", "src:col", collectionName);
                    firstTime = false;
                    doccount++;
                }

                Element result = doc.createElement("result");
                // now add a 'prefix', 'postfix', and 'match'
                String prematch = getMatch(util,0);
                Element pre = doc.createElement("prefix");
                pre.appendChild(doc.createCDATASection(prematch));
                result.appendChild(pre);

                // now attach the match text itself.
                Element m = doc.createElement("match");
				CDATASection matchNode = doc.createCDATASection(util.group(0));
                m.appendChild(matchNode);
                result.appendChild(m);

                // now attach the postfix match
                String postmatchStr = getMatch(util,1);
                Element post = doc.createElement("postfix");
                post.appendChild(doc.createCDATASection(postmatchStr));
                result.appendChild(post);

                outputElement.appendChild(result);
                matchcount++;
            }
            // now attach this newly generated match
            if(outputElement != null)
              root.appendChild(outputElement);

        }

        root.setAttribute( "doccount", Integer.toString( doccount ) );
        root.setAttribute( "matchcount", Integer.toString( matchcount ) );
        return doc;
    }

	/**
	 * Fetch either the prefix match or postfix match.
	 * Those are the characters preceeding the actual grep match or
	 * following it.
	 *
	 * @param util Perl5Util engine which performed the match
	 * @param postfix integer 0 for prefix, 1 for postfix
	 * @return string
	 */
    private String getMatch(Perl5Util util, int postfix)
    {
        String matchStr;

        //org.apache.xindice.Debug.println("getting pre/post match");
        if(postfix==0)
            matchStr = util.preMatch();
        else
            matchStr = util.postMatch();
        int len = matchStr.length();

        // now try to get the prematch text
        if(len < SUBSTRING_LENGTH)
            return matchStr;
        else
            if(postfix==0)
                return matchStr.substring(len-SUBSTRING_LENGTH);
            else
                return matchStr.substring(0,SUBSTRING_LENGTH-1);
    }


	/**
	 *  Creates the Perl regular expression including escaping
	 *  anything that is required.
	 *
	 *  @param re The String containing the requested regex
	 *  @return string representing the perl-friendly regex.
	 */
	private String prepareRegex(String re)
    {
		StringBuffer newReBuf = new StringBuffer("m/");
		StringTokenizer st = new StringTokenizer(re,"/");
		while(st.hasMoreTokens())
		{
		    newReBuf.append(st.nextToken());
		    if(st.countTokens() > 0)
				newReBuf.append("\\/");
		}
		newReBuf.append("/s");
		return newReBuf.toString();
	}

}
