/*
 * @(#)WellKnownServices.java
 *
 * Copyright (c) 2001-2002 JScape
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JScape. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with JScape.
 */

package com.jscape.inet.dns.record;


import com.jscape.inet.dns.DnsInputStream;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;


/**
 * WellKnownServices record is used to describe the well known services supported by
 * a particular protocol on a particular internet address.
 */
public class WellKnownServices
        extends DnsRecord {
    private int[] ipAddress = new int[4];
    private int protocol;
    private byte[] data;

    protected void decode(DnsInputStream inputStream)
            throws IOException {
        for (int j = 0; j < 4; ++j) {
            ipAddress[j] = inputStream.readByte();
        }
        protocol = inputStream.readByte();
        data = new byte[inputStream.available()];
        inputStream.read(data);
    }

    /**
     * Gets <code>byte[]</code> representing 32 bit ip address.
     *
     * @return byte[]
     */
    public byte[] getAddress() {
        byte[] ip = new byte[4];

        for (int j = 0; j < 4; ++j) {
            ip[j] = (byte) ipAddress[j];
        }
        return ip;
    }

    /**
     * Gets InetAddress for this service.
     *
     * @return an InetAddress
     *
     * @throws UnknownHostException the IP address of a host could not be determined
     */
    public InetAddress getInetAddress()
            throws UnknownHostException {
        return InetAddress.getByName(toByteString());
    }

    /**
     * Gets protocol for this service.
     *
     * @return int
     */
    public int getProtocol() {
        return protocol;
    }

    /**
     * Gets data describing this service.
     *
     * @return byte[]
     */
    public byte[] getData() {
        byte[] copy = new byte[data.length];

        System.arraycopy(data, 0, copy, 0, data.length);
        return copy;
    }

    private String toByteString() {
        return ipAddress[0] + "." + ipAddress[1] + "." + ipAddress[2] + "." + ipAddress[3];
    }

    /**
     * Gets String representation of this record.
     *
     * @return String
     */
    public String toString() {
        StringBuffer services = new StringBuffer();

        for (int i = data.length - 1; i >= 0; --i) {
            for (int j = 7; j >= 0; --j) {
                services.append((data[i] >>> j) & 1);
            }
        }
        return getRecordName()
                + "\twell-known services"
                + "\n\taddress = " + toByteString()
                + "\n\tprotocol = " + protocol
                + "\n\tservices = %" + services;
    }
}

