/*
 *  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.IOException;

import phex.utils.GnutellaOutputStream;

public abstract class RouteTableUpdateMsg extends Message
{
    public static final byte RESET_TABLE_VARIANT = 0x00;
    public static final byte PATCH_TABLE_VARIANT = 0x01;

    private byte variant;

    private MsgHeader header;

    public RouteTableUpdateMsg( byte aVariant, int length )
    {
        header = new MsgHeader();
        header.setTTL( (byte)1 );
        header.setPayloadType( MsgHeader.ROUTE_TABLE_UPDATE_PAYLOAD );
        header.setDataLen( length );

        variant = aVariant;
    }

    public RouteTableUpdateMsg( byte aVariant, MsgHeader aHeader )
    {
        header = aHeader;
        variant = aVariant;
    }
    
    public void writeMessage( GnutellaOutputStream outStream )
        throws IOException
    {
        header.writeHeader( outStream );
        outStream.write( variant );
    }

    /**
     * Returns the variant of the RouteTableUpdateMsg. Possible variants are
     * RESET_TABLE_VARIANT, PATH_TABLE_VARIANT.
     * @return the message variant.
     */
    public byte getVariant()
    {
        return variant;
    }

    public int getSize()
    {
        return header.getSize() + header.getDataLen();
    }

    /**
     * Returns this message's header.
     *
     * @return the MsgHeader associated with this message
     */
    public MsgHeader getHeader()
    {
        return header;
    }

    public static RouteTableUpdateMsg parseMessage( MsgHeader header, byte[] aBody )
        throws InvalidMessageException
    {
        // read message variant
        byte variant = aBody[0];

        switch (variant)
        {
            case RESET_TABLE_VARIANT:
                return new QRResetTableMsg( header, aBody );
            case PATCH_TABLE_VARIANT:
                return new QRPatchTableMsg( header, aBody );
            default:
                throw new InvalidMessageException(
                    "Unknown RouteTableUpdateMsg variant");
        }
    }
}