
package de.ivu.elect.presentation;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

import javax.annotation.Nullable;

import de.ivu.elect.business.mandant.entity.Mandant;
import de.ivu.elect.nl.NlElectTreeProperty;

public class NlSystemProperties implements Serializable {

  private static final long serialVersionUID = 1L;

  public Optional<Date> getDefaultWahldatum(Mandant mandant) {
    var defaultElectionDate = NlElectTreeProperty.getDefaultElectionDate();

    if (defaultElectionDate.isPresent()) {
      return defaultElectionDate;
    }

    // Fallback für Demo-System
    if (mandant != null && !mandant.getArt().isOhneMandant()) {
      return extrahiereDatumAusMandantName(mandant.getName());
    }

    return Optional.empty();
  }

  public Optional<Date> getDefaultNominierungstag(Mandant mandant) {
    return NlElectTreeProperty.getDefaultNominationDate();
  }

  public NlElectionLevel getDefaultElectionLevel(Mandant mandant) {
    var nlElectionLevel = NlElectionLevel.UNBEKANNT;

    try {
      // ELECT-9903
      var propertyAsString = System.getProperty("nl.election.level");

      // ELECT-15467
      propertyAsString = propertyAsString.replaceAll("GSB", "PSB");

      nlElectionLevel = NlElectionLevel.valueOf(propertyAsString);
    } catch (Exception ignored) {
    }

    if (nlElectionLevel.isLevelGesetzt()) {
      return nlElectionLevel;
    }

    // Fallback für Demo-System
    if (mandant != null && !mandant.getArt().isOhneMandant()) {
      return extrahiereElectionLevelAusMandantName(mandant.getName());
    }

    return nlElectionLevel;
  }

  private NlElectionLevel extrahiereElectionLevelAusMandantName(String name) {
    Set<NlElectionLevel> result = new HashSet<>();

    try {
      for (String token : name.split("_")) {
        try {
          result.add(NlElectionLevel.valueOf(token));
        } catch (Exception ignored) {
        }
      }
    } catch (Exception ignored) {
    }

    if (result.isEmpty()) {
      return NlElectionLevel.UNBEKANNT;
    }

    if (result.size() == 1) {
      return result.iterator().next();
    }

    return NlElectionLevel.kombiniere(result);
  }

  public boolean isPreventShutdown(@Nullable Mandant mandant) {
    if (Boolean.TRUE.toString().equalsIgnoreCase(System.getProperty("nl.prevent.shutdown"))) {
      return true;
    }

    return mandant != null && !mandant.getArt().isOhneMandant();
  }

  private Optional<Date> extrahiereDatumAusMandantName(String name) {
    try {
      for (var s : name.split("_")) {
        try {
          return Optional.of(new SimpleDateFormat("yyyyMMdd").parse(s));
        } catch (Exception e) {
          // ignore
        }
      }
    } catch (Exception e) {
      // ignore
    }
    return Optional.empty();
  }

}
