/*
 *  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
 * 
 *  --- CVS Information ---
 *  $Id: GGEPExtension.java,v 1.3 2004/01/18 16:55:39 gregork Exp $
 */
package phex.msg;


import phex.host.HostAddress;
import phex.utils.*;

/**
 * Used for parsing GGEP extension data.
 */
public class GGEPExtension
{
    /**
     * Parses the HostAddresses of the ALT GGEP extension.
     * Returns null incase the parsing fails.
     * @param ggepBlocks the GGEP Blocks to look in
     * @return the parsed HostAddresses
     */
    public static HostAddress[] parseAltExtensionData( GGEPBlock[] ggepBlocks )
    {
        // The payload is an array of 6-byte entries.  The first 4 bytes encode
        // the IP of the server (in big-endian, as usual), and the remaining
        // 2 bytes encode the port (in little-endian).
        byte[] altLocData = GGEPBlock.getExtensionDataInBlocks( ggepBlocks,
            GGEPBlock.ALTERNATE_LOCATIONS_HEADER_ID );
            
        if ( altLocData == null )
        {
            return null;
        }
            
        // check for valid length
        if ( altLocData.length % 6 != 0 )
        {
            Logger.logWarning( Logger.NETWORK, "Invalid ALT GGEPBlock length: " + HexConverter.toHexString( altLocData ) );
            return null;
        }
        
        int count = altLocData.length / 6;
        
        HostAddress[] addresses = new HostAddress[ count ];
        int port;
        int offset;
        byte[] ip;
        for ( int i = 0; i < count; i ++ )
        {
            offset = i * 6;
            ip = new byte[4];
            ip[0] = altLocData[ offset ];
            ip[1] = altLocData[ offset + 1 ];
            ip[2] = altLocData[ offset + 2 ];
            ip[3] = altLocData[ offset + 3 ];
            port = IOUtil.unsignedShort2Int(IOUtil.deserializeShortLE( altLocData, offset + 4 ));
            addresses[i] = new HostAddress( ip, port );
        }
        
        return addresses;
    }
}
