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

import java.io.Serializable;

import javax.ejb.Stateless;
import javax.inject.Inject;

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

import de.ivu.elect.business.system.boundary.SystemLogWriter;
import de.ivu.elect.business.system.entity.SystemLogQuelle;
import de.ivu.elect.jee.faces.Messages;

@Stateless
public class NlAirGapCheck implements Serializable {

  private static final long serialVersionUID = 1L;

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

  @Inject
  private transient NlAirGap nlAirGap;

  @Inject
  private transient SystemLogWriter systemLogWriter;

  @Inject
  private transient Messages messages;

  @Inject
  private transient NlAirGapStatusEvent nlAirGapStatusEvent;

  @Inject
  private transient NlAirGapShutdown nlAirGapShutdown;

  public void doIt() {
    LOG.info("Check AirGap");

    try {
      if (isAirGapPresent()) {
        handleAirGapSuccess();
      } else {
        handleAirGapFailed();
      }
    } catch (Exception ex) { // NOSONAR
      systemLogWriter.writeErrorLogMessageFuerSystemMandant(messages.getMessageForMessageKey("nl.air.gap.check.error"), ex, SystemLogQuelle.SYSTEM);
    }
  }

  private boolean isAirGapPresent() throws InterruptedException {
    // ELECT-10561
    if (!nlAirGap.isAirGapPresent()) {
      LOG.info("1 - AirGap not present - reCheck");

      Thread.sleep(1000);

      if (!nlAirGap.isAirGapPresent()) {
        LOG.info("2 - AirGap not present - reCheck");

        Thread.sleep(1000);

        if (!nlAirGap.isAirGapPresent()) {
          LOG.info("3 - AirGap not present");

          return false;
        }
      }
    }

    return true;
  }

  private void handleAirGapFailed() {
    try {
      nlAirGapStatusEvent.sendServerAirGapEvent(true);
    } finally {
      nlAirGapShutdown.doShutdown();
    }
  }

  private void handleAirGapSuccess() {
    nlAirGapStatusEvent.sendServerAirGapEvent(false);

  }
}
