package com.bsmlab.dfx.agent.config.jmx;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;

import org.springframework.context.ConfigurableApplicationContext;

public final class DfxJmxRegistrar {

    private DfxJmxRegistrar() {}

    public static ObjectName register(String agentId, ConfigurableApplicationContext configurableApplicationContext) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            // agentId는 특수문자 가능하므로 quote 처리
            String quotedAgentId = ObjectName.quote(agentId);
            ObjectName name = new ObjectName("com.bsmlab.dfx.agent:type=Control,agentId=" + quotedAgentId);
            if (!mbs.isRegistered(name)) {
                mbs.registerMBean(new DfxAgentControl(configurableApplicationContext), name);
            }
            return name;
        }
        catch (Exception e) {
            throw new IllegalStateException("Failed to register JMX MBean for agentId=" + agentId, e);
        }
    }
}
