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

import javax.enterprise.event.Observes;
import javax.enterprise.event.Reception;
import javax.inject.Inject;

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 de.ivu.elect.business.internet.entity.InternetWidget;
import de.ivu.elect.business.internet.entity.InternetWidgetCustomData;
import de.ivu.elect.business.internet.entity.InternetWidgetFileEntity;

@GroupedConversationScoped
@ConversationGroup(InternetWidgetFileConversationStore.class)
public class InternetWidgetFileConversationStore implements java.io.Serializable {

  private static final long serialVersionUID = 1L;

  @Inject
  protected transient GroupedConversation conversation;

  @Inject
  protected transient InternetWidgetExtendedDAO dao;

  private de.ivu.elect.business.internet.entity.InternetWidgetPK internetWidgetPK;

  private Long position;

  public void setEntityPK(InternetWidgetFileEntity entity, InternetWidget internetWidget) {
    this.internetWidgetPK = internetWidget.getPk();
    this.position = entity.getId();
  }

  public boolean isSelected() {
    return internetWidgetPK != null && position != null;
  }

  public InternetWidgetFileEntity getEntity() {
    if (isSelected()) {
      return dao.findByPrimaryKey(internetWidgetPK).getCustomData(InternetWidgetCustomData.class).getFiles().stream()
          .filter(f -> position.equals(f.getPosition())).map(InternetWidgetFileEntity::new).findFirst().orElse(null);
    }

    return null;
  }

  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();
  }

}
