package cn.quantgroup.xyqb.util;

import org.springframework.core.env.Environment;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;

/**
 * Created by hechao on 2020/1/21.
 */
public abstract class ServerUtils {

    public static Set<ObjectName> getMBeanSet(String name, String attr, String value) throws MalformedObjectNameException {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> names = beanServer.queryNames(new ObjectName(name)
                , Query.match(Query.attr(attr), Query.value(value)));
        return names;
    }

    public static String getHostAddress() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostAddress();
    }

    public static String getPort(Environment environment) throws MalformedObjectNameException {
        Set<ObjectName> mBeanSet = getMBeanSet("*:type=Connector,port=*", "scheme", "domain");
        String port = null;
        if (mBeanSet.size() > 0) {
            port = mBeanSet.iterator().next().getKeyProperty("port");
        }
        if (port == null) {
            port = environment.getProperty("server.port");
        }
        return port;
    }

    public static Long getLongHostAddress(String address) throws UnknownHostException {
        String[] ip = address.split("\\.");
        return (Long.parseLong(ip[0]) << 24) + (Long.parseLong(ip[1]) << 16) + (Long.parseLong(ip[2]) << 8) + Long.parseLong(ip[3]);
    }

    public static Long getLongHostAddress() throws UnknownHostException {
        return getLongHostAddress(getHostAddress());
    }

    public static Integer getIntegerPort(Environment environment) throws MalformedObjectNameException {
        String port = getPort(environment);
        return port == null || port.equals("") ? null : Integer.valueOf(port);
    }


    public static Integer getIntegerPort() throws MalformedObjectNameException {
        return getIntegerPort(null);
    }

    public static void main(String[] args) {
        try {
            System.out.println(ServerUtils.getLongHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

}
