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

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.deltaspike.core.api.scope.ConversationGroup;

import de.ivu.elect.business.wahl.entity.Wahl;

@RequestScoped
@Named(WahlConversationSelect.COMPONENT_NAME)
public class WahlConversationSelect implements java.io.Serializable {

  private static final long serialVersionUID = 1L;

  public static final String COMPONENT_NAME = "wahlConversationSelect";

  @Inject
  protected transient WahlExtendedDAO entityDAO;

  @Inject
  @ConversationGroup(WahlConversationStore.class)
  protected transient WahlConversationStore conversationStore;

  public WahlConversationSelect() {
    super();
  }

  public boolean isSelected() {
    return getEntityPK() != null;
  }

  public Wahl getEntity() {
    return getEntityInternal();
  }

  private Wahl getEntityInternal() {
    if (getEntityPK() == null) {
      return null;
    }

    return attach(getEntityPK());
  }

  public void setEntity(Wahl entity) {
    setEntityAttached(attach(entity));
  }

  public void setEntity( de.ivu.elect.business.wahl.entity.WahlPK  pk) {
    setEntityAttached(attach(pk));
  }

  protected void setEntityAttached(Wahl entity) {
    if(entity == null) {
      setEntityPK(null);
    } else {
      setEntityPK(entity.getPk());
    }
  }

  public
    de.ivu.elect.business.wahl.entity.WahlPK
   getEntityPK() {
    return conversationStore.getEntityPK();
  }

  public void setEntityPK(
    de.ivu.elect.business.wahl.entity.WahlPK
   entityPK) {
    conversationStore.setEntityPK(entityPK);
  }

  protected Wahl attach(Wahl entity) {
    if (entity == null){
      return null;
    }

    return attach(entity.getPk());
  }

  protected Wahl attach( de.ivu.elect.business.wahl.entity.WahlPK  pk) {
    if (pk == null) {
      return null;
    }

    return entityDAO.findByPrimaryKey(pk);
  }

  public void clearEntity() {
    setEntityPK(null);

    conversationStore.close();
  }
}
