/*
 * Written by Dawid Kurzyniec and released to the public domain, as explained
 * at http://creativecommons.org/licenses/publicdomain
 */

package edu.emory.mathcs.util.net.tunnel;

import java.io.*;
import java.net.*;

/**
 * Represents a composite address of tunnelled socket.
 *
 * @author Dawid Kurzyniec
 * @version 1.0
 */
public class TunnelSocketAddress extends SocketAddress {

    final SocketAddress tunnel;
    final int port;

    public TunnelSocketAddress(int port) {
        this(null, port);
    }

    /**
     */
    public TunnelSocketAddress(SocketAddress tunnel, int port) {
//        if (tunnel == null) {
//            tunnel = new InetSocketAddress( (InetAddress)null, 0);
//        }
        if (port < 0) throw new IllegalArgumentException("Port number must be non-negative");
        this.tunnel = tunnel;
        this.port = port;
    }

    public SocketAddress getTunnelAddress() {
        return tunnel;
    }

    /**
     * Returns the logical port number associated with this tunneled socket
     * address.
     *
     * @return logical port number
     */
    public int getPort() {
        return port;
    }

    public int hashCode() {
        return (tunnel == null ? 0 : tunnel.hashCode()) ^ port;
    }

    public boolean equals(Object obj) {
        if (!(obj instanceof TunnelSocketAddress)) return false;
        TunnelSocketAddress that = (TunnelSocketAddress)obj;
        // tunnels can be null
        return (this.tunnel == that.tunnel || this.tunnel.equals(that.tunnel)) &&
            this.port == that.port;
    }

    public String toString() {
        return tunnel + ":" + port;
    }
}
