package de.ivu.elect.presentation.email;

import de.ivu.elect.business.email.boundary.EmailVorlageConversationSelect;
import de.ivu.elect.business.email.boundary.EmailVorlageConversationStore;
import de.ivu.elect.business.email.entity.EmailVorgangType;
import de.ivu.elect.business.email.entity.EmailVorlage;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.jee.presentation.redirect.Redirect;
import de.ivu.elect.presentation.View;
import de.ivu.elect.presentation.hilfe.OnlineHilfeId;
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.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;

@GroupedConversationScoped
@ConversationGroup(EmailVorgangVorlageTestCreateView.class)
@Named(EmailVorgangVorlageTestCreateView.COMPONENT_NAME)
@View(viewId = EmailVorgangVorlageTestCreateView.VIEW_ID, useCase = UseCasePermission.EMAIL_VORGANG_CREATE)
@OnlineHilfeId("741")
public class EmailVorgangVorlageTestCreateView extends AbstractEmailVorgangCreateView {

  private static final long serialVersionUID = 1L;

  public static final String COMPONENT_NAME = "emailVorgangVorlageTestCreateView";

  public static final String VIEW_ID = "/email/email-vorgang-vorlage-test-create.xhtml";

  public static final String PARENT_VIEW_ID = "/email/email-vorlage-search.xhtml";

  @Inject
  private transient GroupedConversation conversation;

  @Inject
  @ConversationGroup(EmailVorlageConversationStore.class)
  private EmailVorlageConversationStore emailVorlageConversationStore;

  @Inject
  private EmailVorlageConversationSelect emailVorlageConversationSelect;

  public EmailVorgangVorlageTestCreateView() {
    super();
  }

  @Override
  protected String getViewId() {
    return VIEW_ID;
  }

  @Override
  protected String getParentViewId() {
    return PARENT_VIEW_ID;
  }

  @Override
  @PostConstruct
  public void init() {
    super.init();

    EmailVorlage emailVorlage = emailVorlageConversationSelect.getEntity();
    getEntity().setTyp(EmailVorgangType.VORLAGE_TEST);
    if (emailVorlage != null) {
      getEntity().setEmailVorlage(emailVorlage);
      getEntity().setBetreff(getMessage("email.vorgang.create.betreff.vorlage.test", emailVorlage.getBezeichnung()));
      getEntity().setInhalt(emailVorlage.getInhalt());
    }
  }

  @Redirect
  public String initWithEmailVorlage(EmailVorlage emailVorlage) {
    conversation.close(); // zunächst eine mögliche bestehende Conversation schließen, um immer mit den Default-Werten zu beginnen
    emailVorlageConversationSelect.setEntity(emailVorlage);
    return reset();
  }

  protected void onClose() {
    emailVorlageConversationStore.close();
    conversation.close();
  }
}
