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

import java.util.Collection;
import java.util.stream.Collectors;

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

import de.ivu.elect.business.benutzerverwaltung.entity.Benutzer;
import de.ivu.elect.business.konfiguration.entity.ElectSystemMandantKonfigurationWerte;
import de.ivu.elect.business.konfiguration.entity.Konfiguration;
import de.ivu.elect.business.konfiguration.entity.KonfigurationInitContext;
import de.ivu.elect.business.mandant.entity.Mandant;
import de.ivu.elect.business.wahl.entity.Wahl;
import de.ivu.elect.business.wahl.entity.Wahltermin;


import static java.util.Objects.isNull;
import static org.apache.commons.lang3.StringUtils.isBlank;

public abstract class AbstractKonfigurationInit extends AbstractCustomParameterInit<ElectSystemMandantKonfigurationWerte, Konfiguration> implements KonfigurationInit {

  private static final String SYSTEM_PROPERTY_PREFIX = "de.ivu.elect.konfiguration.";

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

  private Collection<Konfiguration> parameters;

  public AbstractKonfigurationInit() {
    super();
  }

  @Override
  public Collection<Konfiguration> getDefaultParameters(KonfigurationInitContext konfigurationInitContext) {
    if (isNull(parameters)) {

      parameters = createDefaultParameters(konfigurationInitContext);
    }

    overrideDefaultParameters(konfigurationInitContext.getWahltermin(), konfigurationInitContext.getWahl(), parameters);

    return filter(parameters, konfigurationInitContext.getMandant());
  }

  private Collection<Konfiguration> filter(Collection<Konfiguration> parameters, Mandant mandant) {
    return parameters.stream()
        .filter(parameter -> matchesMandant(parameter, mandant))
        .collect(Collectors.toList());
  }

  private boolean matchesMandant(Konfiguration parameter, Mandant mandant) {
    return  parameter.getTemplate()
        .orElseThrow(()-> new IllegalStateException("Parameter kann weder Systemparameter noch Mandantenparametern zugeordnet werden: '" + parameter.getKey() + "', class: " + getClass()))
        .getKonfigurationMandantArt().isAccept(mandant.getArt());
  }

  protected abstract Collection<Konfiguration> createDefaultParameters(KonfigurationInitContext konfigurationInitContext);

  @Override
  protected Konfiguration create(String key, String value) {
    Konfiguration konfiguration = new Konfiguration();
    konfiguration.setKey(key);

    String valueVorgabeAusSystemProperty = System.getProperty(SYSTEM_PROPERTY_PREFIX + key);

    if (isBlank(valueVorgabeAusSystemProperty)) {
      konfiguration.setWert(value);
    } else {
      konfiguration.setWert(valueVorgabeAusSystemProperty);
    }

    return konfiguration;
  }
}
