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

import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;

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.mandant.boundary.MandantDAO;
import de.ivu.elect.business.mandant.entity.AbstractMandant;
import de.ivu.elect.jee.faces.DevelopmentStore;
import de.ivu.elect.jee.faces.Messages;
import de.ivu.elect.presentation.NlSystemProperties;

@Stateless
public class NlAirGapShutdown {

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

  @Inject
  private transient Messages messages;

  @Inject
  private transient NlSystemProperties nlSystemProperties;

  @Inject
  private transient MandantDAO mandantDAO;

  public void doShutdown() {

    if (isShutdownEnabled()) {
      String shutDownMessage = messages.getMessageForMessageKey("nl.shutdown.message");
      for (int i = 0; i < 10; i++) {
        LOG.error(shutDownMessage);
      }
      for (int i = 0; i < 10; i++) {
        System.out.println(shutDownMessage);
      }
      for (int i = 0; i < 10; i++) {
        System.err.println(shutDownMessage);
      }
      NlWasElectExtendedUseCasePermissionFilter.SHUTDOWN.set(true);

      Timer timer = new Timer(false); // true = daemon !
      timer.schedule(new TimerTask() {
        @Override
        public void run() {
          LOG.info("Shutdown...");
          try {
            Class<?> swarm = Class.forName("org.wildfly.swarm.Swarm");
            Method stopMain = swarm.getMethod("stopMain");
            stopMain.invoke(null);
          } catch (Exception e) {
            // ignorieren
          }

        }
      }, 150);

      timer.schedule(new TimerTask() {
        @Override
        public void run() {
          LOG.info("Shutdown...");
          try {
            MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
            ObjectName objectName = new ObjectName("jboss.as:management-root=server");
            mBeanServer.invoke(objectName, "shutdown", new Object[]{false, 0},
                new String[]{boolean.class.getName(), int.class.getName()});

          } catch (Exception e) {
            // ignorieren
          }

        }
      }, 250);

      try {
        Thread.sleep(10000);
      } catch (InterruptedException e) {
        // ignore
      } finally {
        System.exit(1);
      }

    } else {
      LOG.info("shutdown prevented");
    }

  }

  private boolean isShutdownEnabled() {
    return !nlSystemProperties.isPreventShutdown(AbstractMandant.getSystemMandant(mandantDAO)) && !DevelopmentStore.isDevelopmentStage();
  }
}
