/*
 *  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
 */
package phex.query;

import java.io.IOException;
import java.util.ArrayList;

import phex.common.ThreadPool;
import phex.common.URN;
import phex.common.address.DestAddress;
import phex.connection.BrowseHostConnection;
import phex.connection.BrowseHostException;
import phex.download.RemoteFile;
import phex.msg.GUID;
import phex.msg.QueryResponseMsg;
import phex.msg.QueryResponseRecord;
import phex.utils.NLogger;


public class BrowseHostResults extends Search
{
    public static final short INITIALIZING = 0;
    public static final short CONNECTING = 1;
    public static final short FETCHING = 2;
    public static final short FINISHED = 3;
    public static final short CONNECTION_ERROR = 4;
    public static final short BROWSE_HOST_ERROR = 5;

    private short browseHostStatus;
    private DestAddress destAddress;
    private GUID hostGUID;

    public BrowseHostResults( DestAddress hostAddress, GUID aHostGUID )
    {
        super( );
        this.destAddress = hostAddress;
        hostGUID = aHostGUID;
    }

    public DestAddress getDestAddress()
    {
        return destAddress;
    }

    public GUID getHostGUID()
    {
        return hostGUID;
    }

    public void startSearching()
    {
        isSearching = true;
        Runnable runner = new Runnable()
        {
            public void run()
            {
                BrowseHostConnection connection = new BrowseHostConnection(
                    destAddress, hostGUID, BrowseHostResults.this );
                try
                {
                    connection.sendBrowseHostRequest();
                    browseHostStatus = FINISHED;
                }
                catch ( BrowseHostException exp )
                {
                    NLogger.warn(BrowseHostResults.class, exp, exp);
                    browseHostStatus = BROWSE_HOST_ERROR;
                    stopSearching();
                }
                catch ( IOException exp )
                {// TODO integrate error handling if no results have been returned
                    NLogger.warn(BrowseHostResults.class, exp, exp);
                    browseHostStatus = CONNECTION_ERROR;
                    stopSearching();
                }
            }
        };
        ThreadPool.getInstance().addJob( runner,
            "BrowseHostConnection-" + Integer.toHexString(runner.hashCode()) );
        fireSearchStarted();
    }
    
    public void setBrowseHostStatus( short status )
    {
        browseHostStatus = status;
    }

    public short getBrowseHostStatus()
    {
        return browseHostStatus;
    }

    public void stopSearching()
    {
        isSearching = false;
        fireSearchStoped();
    }
    
    public int getProgress()
    {
        switch ( browseHostStatus )
        {
        case INITIALIZING:
            return 0;
        case CONNECTING:
            return 10;
        case FETCHING:
            return 50;
        case FINISHED:
        case CONNECTION_ERROR:
        case BROWSE_HOST_ERROR:
        default:
            return 100;
        }
    }

    public void processResponse( QueryResponseMsg 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);

            synchronized( this )
            {
                long fileSize = rec.getFileSize();
                String filename = rec.getFilename();
                URN urn = rec.getURN();
                int fileIndex = rec.getFileIndex();
                String metaData = rec.getMetaData();
                String pathInfo = rec.getPathInfo();

                rfile = new RemoteFile( qhHost, fileIndex, filename, pathInfo,
                    fileSize, urn, metaData, (short)100 );
                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 );
        }
    }
    
    public String toString()
    {
        return "[BrowseHostResults:" + destAddress + "," + "@" + Integer.toHexString(hashCode()) + "]";
    }
}