/*
 Copyright (c) 2006 - 2007 Eric J. Feminella  <eric@ericfeminella.com>
 All rights reserved.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is furnished
 to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 @internal
 */

package com.ericfeminella.net
{
    /**
     * 
     * Provides an API for inspecting and validating an IP version 
     * 4 Address (IPv4)
     * 
     * <p>
     * An IP address is 32 bits wide, and is composed of two parts: 
     * the network number, and the host number [1, 2, 3]
     * </p>
     * 
     * <p>
     * By convention, all IP addresses are expressed as four decimal 
     * numbers separated by periods, such as "200.1.2.3", representing 
     * the decimal value of each of the four bytes. Valid addresses 
     * range from 0.0.0.0 to 255.255.255.255, a total of about 4.3 
     * billion addresses. The first few bits of the address indicate 
     * the Class in which the IP address belongs
     * </p>
     * 
     * @example The following example demonstrates a typical use-case
     * which utilizes <code>IPV4Inspector</code> to provide detailed
     * information for a specific IP
     * 
     * <listing version="3.0">
     * 
     * import com.ericfeminella.net.IPV4Inspector;
     * 
     * var ip:IPV4Inspector = new IPV4Inspector("208.113.138.11");
     * 
     * trace( ip.getNetworkClass() ); //Class C
     * trace( ip.isValid() ); //true
     * trace( ip.getNetworkOctet() ); //208
     * trace( ip.getHostOctet() ); //11
     * trace( ip.isLoopback() ); //false
     * trace( ip.isValidNetworkHost() ); //true
     *               
     * </listing>
     * 
     * @see http://en.wikipedia.org/wiki/IPv4
     * 
     */
    public final class IPV4Inspector
    {
        /**
         * 
         * Defines the IP version 4 class A network identifier
         * The valid ip range for a class A network is between
         * 1.0.0.0 to 126.0.0.0
         * 
         */
        public static const CLASS_A:String = "Class A";
        
        /**
         * 
         * Defines the IP version 4 class B network identifier
         * The valid ip range for a class B network is between
         * 128.0.0.0 to 191.255.0.0
         * 
         */
        public static const CLASS_B:String = "Class B";

        /**
         * 
         * Defines the IP version 4 class C network identifier
         * The valid ip range for a class C network is between
         * 192.0.1.0 to 223.255.255.0
         * 
         */
        public static const CLASS_C:String = "Class C";
        
        /**
         * 
         * Defines the IP version 4 class D network identifier
         * The valid ip range for a class D network is between
         * 224.0.0.0 to 239.255.255.255
         * 
         */
        public static const CLASS_D:String = "Class D";

        /**
         * 
         * Defines the IP version 4 class E network identifier
         * The valid ip range for a class E network is between
         * 240.0.0.0 to 255.255.255.255
         * 
         */
        public static const CLASS_E:String = "Class E";
            
        /**
         * 
         * Defines the IP address which has been specified for the 
         * <code>IPV4Inspector</code> instance
         * 
         * @example The following example demonstrates a typical 
         * format for an IP address
         * 
         * <listing version="3.0">
         * 
         * var ip:String = "208.113.138.11";
         * 
         * </listing>
         * 
         */        
        protected var address:String;
        
        /**
         * 
         * Defines the first octet in the IP address which determines 
         * the network class in which the IP address is to grouped
         * 
         * @example The following example demonstrates how to determine
         * the firstoctet of an IP address
         * 
         * <listing version="3.0">
         * 
         * import com.ericfeminella.net.IPV4Inspector;
         * 
         * var ip:IPV4Inspector = new IPV4Inspector("208.113.138.11");

         * trace( ip.getNetworkOctet() ); //208
         *               
         * </listing>
         * 
         */        
        protected var firstOctet:uint;
        
        /**
         * 
         * Defines an array of each individual part, or octet of an 
         * IP addresss
         *   
         */        
        protected var parts:Array;
        
        /**
         * 
         * Creates a new <code>IPV4Inspector</code> instance based on
         * the specified IP address.
         * 
         * <p>
         * Upon instantiation of a new <code>IPV4Inspector</code> object
         * the IP address is validated. If IP address is not in valid IP
         * v4 format an error is thrown
         * </p>
         * 
         * @param the IP Address in which to validate
         * 
         */    
        public function IPV4Inspector(address:String)
        {
            this.address = address;
            
            parts = address.split(".");
            
            if ( parts.length != 4 )
            {
                throw new Error( "Invalid address format exception: " + address );
            }
            firstOctet = uint( parts[0] );
        }
        
        /**
         * 
         * Retrieves the raw IP Address of the <code>IPV4Inspector</code>
         * instance. This is the specified ip address which has not been
         * processed or validated against specific criteria
         * 
         */
        public function getRawIPAddress() : String
        {
            return address;
        }

        /**
         * 
         * Determines if the address specified is a valid IPv4 address
         * 
         * @return true if the IP address is a valid IPv4 address, false if not
         * 
         */
        public function isValid() : Boolean
        {
            var result:Boolean = true;
            
            var pattern:RegExp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
                                 
            if ( address.match( pattern ) != null )
            {
                var n:int = parts.length;
                
                for (var i:int = 0; i < n; i++)
                {
                    var octet:uint = parts[i];
                    
                    if ( octet < 0 || octet > 255 )
                    {
                        result = false;
                        break;
                    }
                }
            }
            return result;
        }
        
        /**
         *
         * Determines if the IP Address is within the Class range 
         * specified
         * 
         * @return true if address is within range, otherwise false
         * 
         */ 
        public function isWithinClassRange(networkClass:String) : Boolean
        {
            var result:Boolean = networkClass == getNetworkClass();
            return result;
        }
        
        /**
         * 
         * Determines if the IP Address is valid for Network assignment
         * 
         * <p>
         * The entire address range of 224.0.0.0 - 255.255.255.255 is 
         * unacceptable for assignment to network hosts, as is any 
         * address beginning with 127
         * </p>
         *
         * @return true if the address is valid, otherwise false
         * 
         */
        public function isValidNetworkHost() : Boolean
        {
            var result:Boolean = true;
            
            if ( firstOctet == 127 || firstOctet >= 224 )
            {
                result = false;
            }
            return result;
        }
        
        /**
         * 
         * Determines if the IP address is a loopback address.
         * 
         * <p>
         * An address starting with 127 is a loopback address and 
         * should never be used for addressing outside of the host
         * </p>
         * 
         * @return true if the address a loopback, otherwise false
         * 
         */
        public function isLoopback() : Boolean
        {
            var result:Boolean = firstOctet == 127;
            return result;
        }
            
        /**
         * 
         * Determines the network class of the specified IP address
         * 
         * <ul>
         *   <li>Class A network octet range: 001 - 126</li>
         *   <li>Class B network octet range: 128 - 191</li>
         *   <li>Class C network octet range: 192 - 223</li> 
         *   <li>Class D network octet range: 224 - 239</li>
         *   <li>Class E network octet range: 240 - 255</li>
         * <ul>
         * 
         * <p>
         * Class D networks are reserved for multicasting and Class E 
         * networks are reserved for "experimental use". All class E 
         * addresses are reserved by the Internet Engineering Task 
         * Force (IETF). Neither Class D or Class E networks should 
         * be assigned to host devices.
         * </p>
         * 
         * @param  IP Address in which to retrieve the network Class
         * @return class of the specified IP Address, Class A,B or C
         * 
         */
        public function getNetworkClass() : String
        {
            var networkClass:String;
            
            if ( firstOctet >= 1 && firstOctet <= 126)
            {
                networkClass = CLASS_A;
            }
            else if ( firstOctet >= 128 && firstOctet <= 191)
            {
                networkClass = CLASS_B;
            }
            else if (firstOctet >= 192 && firstOctet <= 223)
            {
                networkClass = CLASS_C;
            }
            else if (firstOctet >= 224 && firstOctet <= 239) 
            {
                networkClass = CLASS_D;
            }
            else if (firstOctet >= 240 && firstOctet <= 255) 
            {
                networkClass = CLASS_E;
            }
            else
            {
                throw new RangeError("IP out of range Exception: " + firstOctet );
            }
            return networkClass;
        }
        
        /**
         * 
         * Determines the network octet of the specified IP Address
         *
         * @return the network octet of the specified IP Address
         * 
         */
        public function getNetworkOctet() : uint
        {
            return firstOctet;
        }
        
        /**
         * 
         * Determines the host octet of the specified IP Address
         *
         * @return the host octet of the raw IP Address 
         * 
         */
        public function getHostOctet() : String
        {
            var host:String;
            
            switch ( getNetworkClass() )
            {
                case CLASS_A:
                   host = parts[1] + "." + parts[2] + "." + parts[3];
                   break;
                case CLASS_B:
                   host = parts[2] + "." + parts[3];
                   break;    
                case CLASS_C:
                   host = parts[3];
                   break;                      
            }
            return host;
        }
    }
}