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

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

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.enterprise.event.Reception;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.ivu.elect.jee.security.LoginChangeEvent;
import de.ivu.elect.jee.security.LogoutChangeEvent;

@ApplicationScoped
public class NlSessionIpBind implements Serializable {
  private static final long serialVersionUID = 1L;

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

  public static final Map<String, String> IP_ADDRESSE_NACH_SESSION_ID = new ConcurrentHashMap<>();

  public void onLoginChangeEvent(@Observes(notifyObserver = Reception.ALWAYS) LoginChangeEvent loginEvent) {
    try {
      if (StringUtils.isNotBlank(loginEvent.getSessionId()) && loginEvent.getIpHostname() != null && StringUtils.isNotBlank(
          loginEvent.getIpHostname().getIp())) {
        IP_ADDRESSE_NACH_SESSION_ID.put(loginEvent.getIpHostname().getIp(), loginEvent.getSessionId());
      }
    } catch (Exception e) {
      LOG.error("Ip-Session error: " + e.getMessage(), e);
    }

  }

  public void onLogoutChangeEvent(@Observes(notifyObserver = Reception.ALWAYS) LogoutChangeEvent loginEvent) {
    try {
      if (StringUtils.isNotBlank(loginEvent.getSessionId())) {
        IP_ADDRESSE_NACH_SESSION_ID.remove(loginEvent.getSessionId());
      }
    } catch (Exception e) {
      LOG.error("Ip-Session error: " + e.getMessage(), e);
    }
  }

}
