package org.kne.cloud.network.ipv6;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;

public class IPv6AddressGroup implements Comparable<IPv6AddressGroup>{
	
	public IPv6AddressGroup(IPv6Address address) {
		this(address, 128);
	}
	@Override
	public String toString() {
		return address+"/"+prefixLength;
	}
	@Override
	public int hashCode() {
		return Objects.hash(address, prefixLength);
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		IPv6AddressGroup other = (IPv6AddressGroup) obj;
		return Objects.equals(address, other.address) && prefixLength == other.prefixLength;
	}
	public IPv6AddressGroup(IPv6Address address, int prefixLength) {
		super();
		this.address = address;
		this.prefixLength = prefixLength;
	}
	public IPv6AddressGroup(DataInputStream in) throws IOException {
		readFromStream(in);
	}
	private IPv6Address address;
	private int  prefixLength=128;
	public IPv6Address getAddress() {
		return address;
	}
	public int getPrefixLength() {
		return prefixLength;
	}
	
	@Override
	public int compareTo(IPv6AddressGroup o) {
		return -Integer.compare(prefixLength, o.prefixLength);
	}
	public void writeToStream(DataOutputStream out) throws IOException {
		out.writeLong(address.getHigh());
		out.writeLong(address.getLow());
		out.write(prefixLength);
	}
	public void readFromStream(DataInputStream in) throws IOException {
		long high=in.readLong();
		long low=in.readLong();
		address=new IPv6Address(high,low);
		prefixLength=in.read();
	}
	public boolean checkMatch(IPv6Address address2) {
		return address2.equals(address.maskWith(IPv6Address.createMask(prefixLength)));
	}

}
