package de.ivu.elect.business.person.boundary;

import de.ivu.elect.business.person.entity.Personendaten;
import de.ivu.elect.business.person.entity.PersonendatenPK;
import org.apache.deltaspike.core.api.scope.ConversationGroup;
import org.apache.deltaspike.core.api.scope.GroupedConversation;
import org.apache.deltaspike.core.api.scope.GroupedConversationScoped;

import javax.enterprise.event.Observes;
import javax.enterprise.event.Reception;
import javax.inject.Inject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@GroupedConversationScoped
@ConversationGroup(PersonendatenListConversationStore.class)
public class PersonendatenListConversationStore implements Serializable {

  private static final long serialVersionUID = 1L;

  @Inject
  protected transient GroupedConversation conversation;

  @Inject
  protected transient PersonendatenExtendedDAO dao;

  private List<PersonendatenPK> entitiesPKs;

  public List<PersonendatenPK> getEntitiesPKs() {
    return entitiesPKs;
  }

  public void setEntities(List<Personendaten> entities) {
    entitiesPKs = new ArrayList<>(entities.size());
    for (Personendaten entity : entities) {
      entitiesPKs.add(entity.getPk());
    }
  }

  public List<Personendaten> getEntities() {
    List<Personendaten> entities = new ArrayList<>();
    if (isEntitiesSelected()) {
      for (PersonendatenPK entityPK : getEntitiesPKs()) {
        entities.add(dao.findByPrimaryKey(entityPK));
      }
    }
    return entities;
  }

  public boolean isEntitiesSelected() {
    return getEntitiesPKs() != null && !getEntitiesPKs().isEmpty();
  }

  public void close() {
    conversation.close();
  }

  // ELECT-2231    ELECT-2250      ELECT-2267
  /*
   * conversationStore sind von der zur Bearbeitung ausgewählten Wahl abhängig.
   */
  public void onWahlSelectChangeEvent(
      @Observes(notifyObserver = Reception.IF_EXISTS) de.ivu.elect.business.wahl.boundary.WahlSelectChangeEvent event) {
    close();
  }

  /*
   * conversationStore sind vom zur Bearbeitung ausgewählten Wahltermin abhängig.
   */
  public void onWahlterminSelectChangeEvent(
      @Observes(notifyObserver = Reception.IF_EXISTS) de.ivu.elect.business.wahl.boundary.WahlterminSelectChangeEvent event) {
    close();
  }
}
