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

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import de.ivu.elect.business.konfiguration.entity.ElectKonfigurationWerte;
import de.ivu.elect.business.konfiguration.entity.ElectSystemMandantKonfigurationWerte;
import de.ivu.elect.jee.faces.HttpSecurityHeader;

public class HttpHeaderKonfigurationHelper {

  public static final String HTTP_HEADER_PREFIX = "HTTP_HEADER_";
  public static final String HTTP_HEADER_POSTFIX = "_OVERRIDE";

  public static boolean isHttpHeaderParameter(ElectSystemMandantKonfigurationWerte konfigWert) {
    return konfigWert instanceof ElectKonfigurationWerte && konfigWert.name().startsWith(HTTP_HEADER_PREFIX);
  }

  public static List<ElectKonfigurationWerte> getHttpHeaderKonfigurationswerte() {
    return Arrays.stream(ElectKonfigurationWerte.values())
        .filter(HttpHeaderKonfigurationHelper::isHttpHeaderParameter)
        .collect(Collectors.toList());
  }

  public static String getHeaderKeyForParameter(ElectKonfigurationWerte electKonfigurationWerte) {

    try {
      String fieldName = electKonfigurationWerte.name().substring(HTTP_HEADER_PREFIX.length(), electKonfigurationWerte.name().length()-HTTP_HEADER_POSTFIX.length());
      Field f = HttpSecurityHeader.class.getDeclaredField(fieldName);
      f.setAccessible(true);
      Object value = f.get(null);
      return value.toString();
    } catch (Exception e) {
      throw new RuntimeException("Kein Feld gefunden: " + electKonfigurationWerte + ", " + e.getMessage(), e);
    }

  }

}
