package com.bocloud.nms.model.hillstone;

import java.util.Objects;

public class Ipv4 {
    public static long convertIp(String ip) {
    	Objects.nonNull(ip);
        String[] split = ip.split("\\.");
        String ip1 = split[0];
        String ip2 = split[1];
        String ip3 = split[2];
        String ip4 = split[3];
        return (Long.parseLong(ip1) << 24) +
            (Long.parseLong(ip2) << 16) +
            (Long.parseLong(ip3) << 8) +
            Long.parseLong(ip4);
    }

    public static int convertMask(String mask) {
        long maskValue = convertIp(mask);
        String binaryString = Long.toBinaryString(maskValue);
        binaryString = binaryString.replace("0", "");
        return binaryString.length();
    }

    public static long convertUnMask(String unMask) {
        return convertIp(unMask);
    }

    public static String convertIp(long ip) {
        String binaryString = Long.toBinaryString(ip);
        if (binaryString.length() < 32) {
            binaryString = "00000000000000000000000000000000" + binaryString;
            binaryString = binaryString.substring(binaryString.length() - 32);
        }
        String ip1 = binaryString.substring(0, 8);
        String ip2 = binaryString.substring(8, 16);
        String ip3 = binaryString.substring(16, 24);
        String ip4 = binaryString.substring(24, 32);
        return Integer.parseInt(ip1, 2) + "." +
            Integer.parseInt(ip2, 2) + "." +
            Integer.parseInt(ip3, 2) + "." +
            Integer.parseInt(ip4, 2);
    }

    public static String convertMask(long mask) {
        if (mask > 32) {
            return convertIp(mask);
        }
        mask = 32 - mask;
        mask = ((1L << 32) - 1) >> mask << mask;
        return convertIp(mask);
    }

    public static String convertUnMask(long unMask) {
        return convertIp(unMask);
    }
}
