
package de.ivu.elect.presentation.email;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;

import de.ivu.elect.business.email.boundary.CommonEmailVorlageBoundaryCreate;
import de.ivu.elect.business.email.entity.AbstractEmailVorgang;
import de.ivu.elect.business.email.entity.EmailVorlage;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.business.security.UseCaseSecure;
import de.ivu.elect.business.wahl.boundary.WahlterminNichtAusgewaehltException;
import de.ivu.elect.jee.faces.HttpHeaderContentSecurityPolicy;
import de.ivu.elect.jee.faces.PreConditionCheck;
import de.ivu.elect.jee.presentation.dynamicform.FormBuilder;
import de.ivu.elect.jee.presentation.redirect.Redirect;
import de.ivu.elect.presentation.email.form.EmailVorlageViewFormBuilder;
import de.ivu.elect.presentation.hilfe.OnlineHilfeId;

@Named(AbstractEmailVorlageCreateView.COMPONENT_NAME)
@OnlineHilfeId(value = "737", mehrfachVergebenOk = true)
@HttpHeaderContentSecurityPolicy(policy="script-src", add="'unsafe-eval'")
public class EmailVorlageCreateView extends AbstractEmailVorlageCreateView {

  private static final long serialVersionUID = 1L;

  @Inject
  private transient CommonEmailVorlageBoundaryCreate create;

  @Inject
  private EmailVorlageViewFormBuilder emailVorlageViewFormBuilder;

  public EmailVorlageCreateView() {
    super();
  }

  @Override
  @PostConstruct
  public void init() {
    super.init();
    getEntity().setInhalt(AbstractEmailVorgang.getInhaltDefaultValue());
  }

  @PreConditionCheck
  public String checkPreCondition() {
    if (!isWahlterminSelected() && !isWahlSelected()) {
      throw new WahlterminNichtAusgewaehltException();
    }
    return null;
  }

  @Override
  @Redirect
  @UseCaseSecure(UseCasePermission.EMAIL_VORLAGE_CREATE)
  public String save() {
    checkPreCondition();

    create.save(getEntity(), getSelectedWahl(), getSelectedWahltermin());

    addMessageSaveSuccess(getEntity());

    resetStateAfterAction();

    return goBack(getParentViewId());
  }

  @Override
  public void addProperties(FormBuilder formBuilder, EmailVorlage emailVorlage) {
    checkPreCondition();
    emailVorlageViewFormBuilder.addEmailVorlagePropertiesWithDefaultValues(formBuilder, emailVorlage);
  }
}
