package de.ivu.elect.business.system.control;

import java.lang.management.ManagementFactory;

import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.ivu.elect.business.system.entity.PreShutdownEvent;

@Stateless
public class WildFlyServerAsync {

  private static final Logger LOG = LoggerFactory.getLogger(WildFlyServerAsync.class);

  @Inject
  private transient PreShutdownEvent preShutdownEvent;

  @Inject
  private transient KillProcess killProcess;

  @Asynchronous
  public void shutdown(Long delayInMs) {
    LOG.info("Shutdown async: " + delayInMs);
    preShutdownEvent.sendEvent();
    try {
      Thread.sleep(delayInMs);
    } catch (Exception e) {
      // ignore
    }

    LOG.info("Shutdown management...");
    try {
      // Über Management Konsole
      MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
      ObjectName objectName = new ObjectName("jboss.as:management-root=server");
      mBeanServer.invoke(objectName, "shutdown", new Object[]{false, 0, 0},
          new String[]{boolean.class.getName(), int.class.getName(), int.class.getName()});
    } catch (Exception e) {
      LOG.warn("Shutdown management impossible: " + e.getMessage());
      // ELECT-15143 fallback über kill command senden
      LOG.info("Shutdown kill...");
      try {
        if (killProcess.sendKill()) {
          LOG.info("Shutdown kill sent");
        } else {
          LOG.warn("Shutdown kill failed");
        }
      } catch (Exception e1) {
        LOG.error("Shutdown kill failed: " + e1.getMessage());
      }
    }

  }
}
