/*
 *  PHEX - The pure-java Gnutella-servent.
 *  Copyright (C) 2001 - 2006 Phex Development Group
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 *  --- CVS Information ---
 *  $Id: KeywordSearch.java 3362 2006-03-30 22:27:26Z gregork $
 */
package phex.query;

import java.util.ArrayList;
import java.util.StringTokenizer;

import phex.common.ServiceManager;
import phex.common.URN;
import phex.common.address.DestAddress;
import phex.connection.NetworkManager;
import phex.download.RemoteFile;
import phex.msg.*;
import phex.utils.SearchEngine;

public class KeywordSearch extends Search
{    
    /**
     * The String that is beeing searched for.
     */
    private String searchString;

    /**
     * The URN that is beeing searched for.
     */
    private URN searchURN;


    public KeywordSearch( String aSearchString )
    {
        this( aSearchString, null );
    }

    public KeywordSearch( String aSearchString, URN aSearchURN )
    {
        searchString = aSearchString;
        searchURN = aSearchURN;

        boolean isPhexBehindFirewall = !NetworkManager.getInstance()
            .hasConnectedIncoming();
        queryMsg = new QueryMsg( (byte)ServiceManager.sCfg.ttl, searchString,
            searchURN, QueryMsg.IS_PHEX_CAPABLE_OF_XML_RESULTS,
            isPhexBehindFirewall);
    }
    
    public String getSearchString()
    {
        return searchString;
    }
    
    public void setSearchString( String aSearchString )
    {
        searchString = aSearchString;
        searchURN = null;
        boolean isPhexBehindFirewall = !NetworkManager.getInstance()
            .hasConnectedIncoming();
        queryMsg = new QueryMsg( (byte)ServiceManager.sCfg.ttl, searchString,
            searchURN, QueryMsg.IS_PHEX_CAPABLE_OF_XML_RESULTS,
            isPhexBehindFirewall);
        fireSearchChanged();
    }

    public void processResponse( QueryResponseMsg msg )
    {
        //we like to receive results even if the query was stopped already.
        
        // check if it is a response for this query?
        if (!msg.getHeader().getMsgID().equals( queryMsg.getHeader().getMsgID()))
        {
            return;
        }

        // remoteHost.log("Got response to my query.  " + msg);
        long speed = msg.getRemoteHostSpeed();
        GUID rcID = msg.getRemoteClientID();
        DestAddress address = msg.getDestAddress();

        QueryHitHost qhHost = new QueryHitHost( rcID, address, speed );
        qhHost.setQHDFlags( msg.getPushNeededFlag(), msg.getServerBusyFlag(),
            msg.getHasUploadedFlag(), msg.getUploadSpeedFlag() );
        qhHost.setQueryResponseFields( msg );

        QueryResponseRecord rec;
        RemoteFile rfile;

        int recordCount = msg.getRecordCount();
        ArrayList newHitList = new ArrayList( recordCount );
        for (int i = 0; i < recordCount; i++)
        {
            rec = msg.getMsgRecord(i);

            // verify record when using a urn query
            // this acts like a filter but there seem to be no need to make this
            // not permanet...
            if ( searchURN != null && rec.getURN() != null )
            {
                if ( !searchURN.equals( rec.getURN() ) )
                {
                    continue;
                }
            }

            synchronized( this )
            {
                long fileSize = rec.getFileSize();
                String filename = rec.getFilename();
                URN urn = rec.getURN();
                int fileIndex = rec.getFileIndex();
                String metaData = rec.getMetaData();
                
                // search string might be null in case whats new search is used
                short score = searchString == null ? 100 : 
                    KeywordSearch.calculateSearchScore( searchString, filename );
                
                // find duplicate from same host...
                RemoteFile availableHit = searchResultHolder.findQueryHit( 
                    qhHost, urn, filename, fileSize, fileIndex );
                
                if ( availableHit != null )
                {
                    // update availableHit
                    availableHit.updateQueryHitHost( qhHost );
                    availableHit.setMetaData( metaData );
                }
                else
                {
                    String pathInfo = rec.getPathInfo();
                    rfile = new RemoteFile( qhHost, fileIndex, filename, pathInfo,
                        fileSize, urn, metaData, score );
                    searchResultHolder.addQueryHit( rfile );
                    newHitList.add( rfile );
                }
                // handle possible AlternateLocations
                DestAddress[] alternateLocations = rec.getAlternateLocations();
                if ( urn != null && alternateLocations != null)
                {
                    for ( int j = 0; j < alternateLocations.length; j++ )
                    {
                        // find duplicate from same host...
                        QueryHitHost qhh = new QueryHitHost( null, alternateLocations[j], -1 );
                        
                        availableHit = searchResultHolder.findQueryHit( qhHost,
                            urn, filename, fileSize, fileIndex );
                        if ( availableHit != null )
                        {
                            // update availableHit
                            availableHit.updateQueryHitHost( qhHost );
                            availableHit.setMetaData( metaData );
                        }
                        else
                        {
                            rfile = new RemoteFile( qhh, -1, filename, "", 
                                fileSize, urn, metaData, score );
                            searchResultHolder.addQueryHit( rfile );
                            newHitList.add( rfile );
                        }
                    }
                }
            }
        }
        // if something was added...
        if ( newHitList.size() > 0 )
        {
            if ( queryEngine != null )
            {
                queryEngine.incrementResultCount( newHitList.size() );
            }
            RemoteFile[] newHits = new RemoteFile[ newHitList.size() ];
            newHitList.toArray( newHits );
            fireSearchHitsAdded( newHits );
        }
    }
    
    /**
     * This methods calculates the score of a search result. The return value is
     * between 0 and 100. A value of 100 means all terms of the search string
     * are matched 100% in the result string.
     */
    public static short calculateSearchScore( String searchStr, String resultStr )
    {
        double tokenCount = 0;
        double hitCount = 0;
        StringTokenizer tokens = new StringTokenizer( searchStr );
        SearchEngine searchEngine = new SearchEngine();
        searchEngine.setText(resultStr, false);
        while ( tokens.hasMoreTokens() )
        {
            String token = tokens.nextToken();
            tokenCount ++;
            searchEngine.setPattern( token, false );
            if ( searchEngine.match() )
            {
                hitCount ++;
            }
        }
        double perc = hitCount / tokenCount * 100;
        return (short) perc;
    }
    
    public String toString()
    {
        return "[KeywordSearch:" + searchString + "," + super.toString() + "]";
    }
}