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

import javax.inject.Inject;

import de.ivu.elect.jee.faces.HttpHeaderContentSecurityPolicies;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.ivu.elect.jee.faces.HttpHeaderContentSecurityPolicy;
import de.ivu.elect.jee.faces.HttpHeaderContentSecurityPolicyContent;
import de.ivu.elect.jee.faces.HttpSecurityHeader;
import de.ivu.elect.jee.startup.PostStartup;
import de.ivu.elect.presentation.View;
import de.ivu.elect.presentation.ui.ViewIterator;

/**
 * HTTP Header konfigurierbar
 */
public class HttpHeaderKonfigurationPostStartup implements PostStartup {

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

  @Inject
  private transient HttpHeaderKonfigurationAktualisieren httpHeaderKonfigurationAktualisieren;

  @Inject
  private transient ViewIterator viewIterator;

  @Override
  public void postStartup() {
    if (Boolean.TRUE.toString().equalsIgnoreCase(System.getProperty("ivu.elect.skip.init.http.header"))) {
      LOG.warn("HTTP-Header NICHT initialisiert => defaults: " + HttpSecurityHeader.HEADER_MAP);
    } else {
      httpHeaderKonfigurationAktualisieren.aktualisiereHttpHeader();
    }

    LOG.info("Suche HttpHeaderContentSecurityPolicy");
    viewIterator.iterateViews(view -> {
      HttpHeaderContentSecurityPolicy httpHeaderContentSecurityPolicy = view.getClass().getAnnotation(HttpHeaderContentSecurityPolicy.class);
      HttpHeaderContentSecurityPolicies httpHeaderContentSecurityPolicies = view.getClass().getAnnotation(HttpHeaderContentSecurityPolicies.class);
      if (httpHeaderContentSecurityPolicy != null || httpHeaderContentSecurityPolicies != null) {
        View viewAnnotation = view.getClass().getAnnotation(View.class);
        if (viewAnnotation != null) {
          if (httpHeaderContentSecurityPolicy != null) {
            LOG.info("HttpHeaderContentSecurityPolicy found " + viewAnnotation + ", " + httpHeaderContentSecurityPolicy);
            HttpSecurityHeader.addCsp(viewAnnotation.viewId(), new HttpHeaderContentSecurityPolicyContent(httpHeaderContentSecurityPolicy));
          }
          if (httpHeaderContentSecurityPolicies != null) {
            LOG.info("HttpHeaderContentSecurityPolicies found " + viewAnnotation + ", " + httpHeaderContentSecurityPolicies);
            HttpSecurityHeader.addCsp(viewAnnotation.viewId(), new HttpHeaderContentSecurityPolicyContent(httpHeaderContentSecurityPolicies));
          }
        }
      }

    });
    LOG.info("Suche HttpHeaderContentSecurityPolicy - done");
  }

}
