/*
 *  PHEX - The pure-java Gnutella-servent
 *  Copyright (C) 2001 - 2004 Gregor Koukkoullis ( phex <at> kouk <dot> de )
 *
 *  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.msg;

import java.io.*;


import phex.utils.*;


/**
 * <p>A Gnutella Ping message.</p>
 *
 * <p>This represents a ping message. It informs other Gnutella nodes that this
 * node wants to know about them. The responses to this will be pongs,
 * encapsulated by the MsgInitResponse class.</p>
 *
 * <p>This implementation handles GGEP extension blocks.</p>
 */
public class MsgPing extends Message
{
    private MsgHeader header;

    /**
     * <p>The un-parsed body of the message.</p>
     * It might include the optional payload.
     */
    private byte[] body;

    /**
     * Create a new init message with a default header.
     */
    public MsgPing()
    {
        header = new MsgHeader();
        header.setPayloadType( MsgHeader.PING_PAYLOAD );
        header.setDataLen( 0 );
        body = IOUtil.EMPTY_BYTE_ARRAY;
    }

    /**
     * <p>Create a new init message using a header.</p>
     *
     * <p>This will set the function property of the header to MsgHeader.sInit.
     * </p>
     *
     * @param header  the MsgHeader to use
     */
    public MsgPing( MsgHeader aHeader, byte[] aBody )
    {
        header = aHeader;
        header.setPayloadType( MsgHeader.PING_PAYLOAD );
        body = aBody;
        header.setDataLen( body.length );
    }

    public MsgHeader getHeader()
    {
        return header;
    }

    /**
     * Returns the size of the message in bytes.
     */
    public int getSize()
    {
        return header.getSize() + header.getDataLen();
    }
    
    public void writeMessage( GnutellaOutputStream outStream )
        throws IOException
    {
        header.writeHeader( outStream );
        outStream.write( body, 0, body.length );
    }

    public String toString()
    {
        return	getDebugString();
    }

    public String getDebugString()
    {
        return "Ping[ HEX=[" + HexConverter.toHexString( body ) +
            "] ]";
    }

}

