package net.northking.cctp.element.util;

import net.northking.cctp.element.core.APIFactory;
import net.northking.cctp.element.core.exception.AssertException;
import net.northking.cctp.element.log.Logger;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;

/**
 * @author fengxiang.zhang
 * @since 1.0
 */
public class ComponentUtils {

    private static Logger logger = APIFactory.getLogger();

    private static String Local_Host_Mac;

    static {
        try {
            Local_Host_Mac = getLocalHostMac();
        } catch (Exception e) {
        }
    }

    /**
     * 组件断言失败时抛出断言异常。
     *
     * @param error 组件默认断言失败信息
     * @param msg   用户输入的断言失败信息
     * @throws AssertException
     */
    public static void assertFail(String error, String msg) throws AssertException {
        Assert.hasText(error);
        if (StringUtils.isBlank(msg)) {
            throw new AssertException(error);
        } else {
            logger.error(error);
            throw new AssertException(msg);
        }
    }

    public static String getLocalHostMac() throws Exception {
        return Local_Host_Mac == null ? getMac(InetAddress.getLocalHost()) : Local_Host_Mac;
    }

    private static String getMac(InetAddress ia) throws Exception {
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            String s = Integer.toHexString(mac[i] & 0xFF);
            sb.append(s.length() == 1 ? 0 + s : s);
        }
        return sb.toString().toUpperCase();
    }

}