/*
 This file is part of GNUnet.
  (C) 2012, 2013 Christian Grothoff (and other contributing authors)

  GNUnet 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 3, or (at your
  option) any later version.

  GNUnet 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 GNUnet; see the file COPYING.  If not, write to the
  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.
 */

package org.gnunet.gns.records;


import com.google.common.net.InetAddresses;
import org.gnunet.construct.FixedSizeIntegerArray;
import org.gnunet.construct.UnionCase;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * A DNS A Record.
 */
@UnionCase(1)
public class ARecordData implements RecordData {

    @FixedSizeIntegerArray(length = 4, bitSize = 8, signed = false)
    public byte[] addr;

    @SuppressWarnings("UnusedDeclaration")
    public static String recordTypeString = "A";

    public static ARecordData fromString(String s) {
        InetAddress addr = InetAddresses.forString(s);
        byte[] addrBytes = addr.getAddress();
        if (addrBytes.length != 4) {
            return null;
        }
        ARecordData recordData = new ARecordData();
        recordData.addr = addrBytes;
        return recordData;
    }

    @Override
    public String asRecordString() {
        if (addr.length != 4) {
            return null;
        }
        InetAddress inetAddress;
        try {
            inetAddress = Inet4Address.getByAddress(addr);
        } catch (UnknownHostException e) {
            return null;
        }
        return inetAddress.getHostAddress();
    }
}
