
package de.ivu.elect.presentation.protokollierung.action;

import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;

import javax.annotation.Nonnull;
import javax.inject.Inject;

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

import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.jee.entity.Entity;
import de.ivu.elect.jee.entity.ExtendedDAO;
import de.ivu.elect.jee.entity.tk.EntityUK;
import de.ivu.elect.presentation.View;
import de.ivu.elect.presentation.menu.AbstractActionEntry;
import de.ivu.elect.presentation.protokollierung.ProtokollEintragSearchView;
import de.ivu.elect.presentation.security.AbstractGebietSecurity;

public class ProtokollAnzeigenActionEntry extends AbstractActionEntry<Entity<Object, EntityUK>> {

  private static final long serialVersionUID = 1L;

  private static final Logger LOGGER = LoggerFactory.getLogger(ProtokollAnzeigenActionEntry.class);

  @Inject
  private transient ExtendedDAO extendedDao;

  @View
  @Inject
  private transient ProtokollEintragSearchView protokollEintragSearchView;

  public ProtokollAnzeigenActionEntry() {
    super();
  }

  @Override
  public UseCasePermission getRequiredPermission() {
    return UseCasePermission.PROTOKOLL_EINTRAG_SEARCH;
  }

  @Override
  public AbstractGebietSecurity getGebietSecurity() {
    return KEINE_GEBIET_SECURITY;
  }

  @Override
  public boolean isDisabled(Entity<Object, EntityUK> proxy) {
    boolean disabledAnyway = isNull(proxy) || !tryCastToEntity(proxy).isAenderungenProtokollieren();

    // ELECT-5246
    return disabledAnyway || super.isDisabled(proxy);
  }

  @Override
  public boolean isDisabledInternal(@Nonnull Entity<Object, EntityUK> entity) {
    return !entity.isAenderungenProtokollieren();
  }

  @Override
  protected String doIt(Entity<Object, EntityUK> entity) {
    return protokollEintragSearchView.showWithEntity(entity);
  }

  @Override
  protected boolean isFireChangeEvent() {
    return false;
  }

  @Override
  protected void fireChangeEvent() {
    // nichts zu tun
  }

  @Override
  public String getLabelKey() {
    return "entity.edit.action.protokoll";
  }

  @Override
  public String getIcon() {
    return appIcons.getIconClock();
  }

  @Override
  protected Entity<Object, EntityUK> attach(Entity<Object, EntityUK> entity) {
    if (nonNull(entity) && nonNull(entity.getId()) && entity.getId() != Long.MIN_VALUE /* Spezialfall für nicht persistente Entitäten */) {
      try {
        // ELECT-5056
        return extendedDao.getEntityManager().find(entity.getClass(), entity.getId());
      } catch (Exception ex) {
        LOGGER.warn("FAILED to attach entity [id = " + entity.getId() + ", class = " + entity.getClass() + "]", ex);
      }
    }

    return entity;
  }
}
