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

import java.util.stream.Collectors;

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.DbScript;
import de.ivu.elect.business.system.entity.SystemLogQuelle;
import de.ivu.elect.jee.database.DatasourceJndiResolver;
import de.ivu.elect.jee.startup.PostStartupAsync;

public class DbInitializerCheckPostStartup implements PostStartupAsync {

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

  @Inject
  private transient DatasourceJndiResolver datasourceJndiResolver;

  @Inject
  private transient SystemLogWriter systemLogWriter;

  @Inject
  private transient ElectDbInitializerSqlRunner electDbInitializerSqlRunner;

  @Override
  public void postStartup() {
    LOG.info("Check DB Update");
    try {
      var datasource = datasourceJndiResolver.getDatasource();
      var skripteNichtErfolgreich = electDbInitializerSqlRunner.getSkripteNichtErfolgreich(datasource);
      if (skripteNichtErfolgreich.isEmpty()) {
        LOG.info("Check DB Update - done");
      } else {
        systemLogWriter.writeErrorLogMessageFuerSystemMandant(
            "Check DB-Updates: " + skripteNichtErfolgreich.stream().map(DbScript::getName).collect(Collectors.joining(", ")),
            SystemLogQuelle.SYSTEM);
      }

    } catch (Exception e) {
      systemLogWriter.writeErrorLogMessageFuerSystemMandant("DB check failed", e, SystemLogQuelle.SYSTEM);
    }

  }
}
