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 Logger LOG = LoggerFactory.getLogger(NlAirGapCheck.class);

  private static final long serialVersionUID = 1L;

  @Inject
  private transient NlAirGap nlAirGap;

  @Inject
  private transient SystemLogWriter systemLogWriter;

  @Inject
  private transient Messages messages;

  @Inject
  private transient NlAirGapHandlerNewTransaction nlAirGapHandlerNewTransaction;

  @Inject
  private transient NlAirGapShutdown nlAirGapShutdown;

  public void doIt() {
    LOG.info("Check AirGap");
    try {
      if (isAirGapPresent()) {
        handleAirGapSuccess();
      } else {
        handleAirGapFailed();
      }
    } catch (Exception e) {
      systemLogWriter.writeErrorLogMessageFuerSystemMandant(messages.getMessageForMessageKey("nl.air.gap.check.error"), e, 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() {
    nlAirGapHandlerNewTransaction.handleAirGapFailed();
    nlAirGapShutdown.doShutdown();
  }

  private void handleAirGapSuccess() {
    nlAirGapHandlerNewTransaction.handleAirGapSuccess();
  }

}
