
package de.ivu.elect.presentation;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;

import de.ivu.elect.business.benutzerverwaltung.boundary.AngemeldeteBenutzer;
import de.ivu.elect.business.benutzerverwaltung.control.LogoutException;
import de.ivu.elect.business.benutzerverwaltung.entity.BenutzerEinsatzort;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.business.security.control.ElectCommonPrincipal;
import de.ivu.elect.jee.faces.security.AbstractSecurityViewValidator;

@RequestScoped
@Named(AbstractSecurityViewValidator.SECURITY_VIEW_VALIDATOR_NAME)
public class UseCaseSecurityViewValidator extends AbstractSecurityViewValidator<UseCasePermission, View> {

  @Inject
  private transient AngemeldeteBenutzer angemeldeteBenutzer;

  @Inject
  private transient ElectCommonPrincipal electCommonPrincipal;

  @Inject
  @View
  private transient Instance<Object> views;

  public UseCaseSecurityViewValidator() {
    super();
  }

  @Override
  public Iterable<Object> getAllViews() {
    return views;
  }

  @Override
  protected String getViewId(View viewAnnotation) {
    return viewAnnotation.viewId();
  }

  @Override
  @SuppressWarnings("rawtypes")
  protected Class getViewAnnotationClass() {
    return View.class;
  }

  @Override
  protected boolean isKeinUseCaseAngegben(View view) {
    return view.useCase() == null || UseCasePermission.UNSINN.equals(view.useCase());
  }

  @Override
  protected boolean isPermissionErfuellt(View view) {
    return UseCasePermission.OHNE.equals(view.useCase()) || principal.hasUseCasePermission(view.useCase());
  }

  @Override
  protected UseCasePermission getRequiredPermission(View view) {
    return view.useCase();
  }

  @Override
  public void checkView(String viewId) {
    super.checkView(viewId);
    if (principal.isLoggedIn() && StringUtils.isNotBlank(electCommonPrincipal.getSessionId())) {
      try {
        if (!angemeldeteBenutzer.interaction(electCommonPrincipal.getSessionId())) {
          BenutzerEinsatzort benutzerEinsatzort = electCommonPrincipal.getBenutzerEinsatzort();
          angemeldeteBenutzer.login(electCommonPrincipal.getSessionId(),
              electCommonPrincipal.getLogin().getPk(),
              electCommonPrincipal.getMandant().getNummer(),
              electCommonPrincipal.getName(),
              electCommonPrincipal.getIpHostname(),
              electCommonPrincipal.getLogin().getRollenAsStrings(benutzerEinsatzort), benutzerEinsatzort);
        }
      } catch (LogoutException le) {
        principal.logout();
        throw le;
      }
    }
  }

}
