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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.inject.Inject;

import de.ivu.elect.business.CurrentCustomer;
import de.ivu.elect.business.konfiguration.entity.ElectKonfigurationWerte;
import de.ivu.elect.business.konfiguration.entity.Konfiguration;
import de.ivu.elect.business.konfiguration.entity.KonfigurationInitContext;
import de.ivu.elect.business.system.control.BackgroundServiceRetry;
import de.ivu.elect.business.version.boundary.AbstractVersion;

public class SystemKonfigurationInit extends AbstractKonfigurationInit {

  @Inject
  private transient CurrentCustomer currentCustomer;

  @Inject
  private transient AbstractVersion abstractVersion;

  @Override
  protected Collection<Konfiguration> createDefaultParameters(KonfigurationInitContext konfigurationInitContext) {
    List<Konfiguration> result = new ArrayList<>();
    add(result, ElectKonfigurationWerte.SYSTEM_ID, getSystemId());
    add(result, ElectKonfigurationWerte.CUSTOMER, currentCustomer.getCustomer());
    add(result, ElectKonfigurationWerte.VERSION, getVersionString(abstractVersion));
    add(result, ElectKonfigurationWerte.LOGIN_SERVICE_ADMIN_SPERREN, true);
    add(result, ElectKonfigurationWerte.BACKGROUND_SERVICE_MAX_ERROR_COUNT, BackgroundServiceRetry.MAX_ERROR_COUNT_DEFAULT);
    add(result, ElectKonfigurationWerte.BACKGROUND_SERVICE_RESTART_CRON_TIMER, "15,45 * * * *");
    return result;
  }

  public static String getVersionString(AbstractVersion abstractVersion) {
    String number = abstractVersion.getNumber();
    Date date = abstractVersion.getTimestamp();

    if (number == null) {
      number = "<>";
    }

    if (date == null) {
      date = new Date();
    }

    return number + " - " + new SimpleDateFormat("yyyyMMddHHmm").format(date);
  }

  protected String getSystemId() {
    return UUID.randomUUID().toString();
  }
}
