
package de.ivu.elect.presentation.system.menu;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.inject.Inject;

import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.business.system.boundary.SystemLogExtendedDAO;
import de.ivu.elect.business.system.entity.LogNachrichtArt;
import de.ivu.elect.business.system.entity.SystemLogStatus;
import de.ivu.elect.presentation.system.SystemLogSearchView;

public class SystemLogSearchMenuItemEntry extends AbstractSystemLogMenuItemEntry {

  private static final long serialVersionUID = 1L;

  @Inject
  private transient SystemLogExtendedDAO systemLogDao;

  private long systemLogCount;

  private final Map<LogNachrichtArt, Long> countNachArt = new ConcurrentHashMap<>();

  public SystemLogSearchMenuItemEntry() {
    super();

    this.systemLogCount = -1;

    this.countNachArt.clear();
  }

  @Override
  protected UseCasePermission getUseCasePermission() {
    return UseCasePermission.SYSTEM_LOG_SEARCH;
  }

  @Override
  public String getTargetViewId() {
    return SystemLogSearchView.VIEW_ID;
  }

  public long getSystemLogCount() {
    if (isRendered() && systemLogCount < 0) {
      systemLogCount = 0;

      for (LogNachrichtArt logNachrichtArt : LogNachrichtArt.values()) {
        systemLogCount += getSystemLogCount(logNachrichtArt);
      }
    }

    return systemLogCount;
  }

  public long getSystemLogCount(LogNachrichtArt logNachrichtArt) {
    if (isRendered()) {
      return countNachArt.computeIfAbsent(logNachrichtArt, x -> {
        Long count = systemLogDao.findByCountStatusArt(getPrincipal().getMandant(), SystemLogStatus.ZU_PRUEFEN, logNachrichtArt);

        if (logNachrichtArt.isPopupMessageAnzeigen() && count > 0) {
          logNachrichtArt.createMessage(getMessages(), count);
        }

        return count;
      });
    }

    return 0L;
  }

  @Override
  public String getLabelKey() {
    return "system.log.search.menu.item.label";
  }

  @Override
  public String getIcon() {
    return getIcons().getIconWarning();
  }
}
