
package de.ivu.elect.presentation.email;

import de.ivu.elect.business.email.boundary.EmailVorgangExtendedDAO;
import de.ivu.elect.business.email.boundary.EmailVorlageExtendedDAO;
import de.ivu.elect.business.email.entity.EmailLayout;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.business.security.UseCaseSecure;
import de.ivu.elect.jee.presentation.dynamicform.FormBuilder;
import de.ivu.elect.jee.presentation.redirect.Redirect;
import de.ivu.elect.presentation.email.form.EmailLayoutViewFormBuilder;
import de.ivu.elect.presentation.hilfe.OnlineHilfeId;

import javax.inject.Inject;
import javax.inject.Named;

@Named(AbstractEmailLayoutEditView.COMPONENT_NAME)
@OnlineHilfeId(value = "740", mehrfachVergebenOk = true)
public class EmailLayoutEditView extends AbstractEmailLayoutEditView {

  private static final long serialVersionUID = 1L;

  @Inject
  private EmailLayoutViewFormBuilder emailLayoutViewFormBuilder;

  @Inject
  private transient EmailVorgangExtendedDAO emailVorgangDao;

  @Inject
  private transient EmailVorlageExtendedDAO emailVorlageDao;

  public EmailLayoutEditView() {
    super();
  }

  @Override
  protected boolean isGebietBearbeitenRechtPruefen() {
    return false;
  }

  @Override
  public void addProperties(FormBuilder formBuilder, EmailLayout emailLayout) {
    emailLayoutViewFormBuilder.addEmailLayoutProperties(formBuilder, emailLayout);
  }

  @Override
  @Redirect
  @UseCaseSecure(UseCasePermission.EMAIL_LAYOUT_DELETE)
  public String delete() {
    if (!isDeletePossible()) {
      return null;
    }
    return super.delete();
  }

  private boolean isDeletePossible() {
    EmailLayout emailLayout = getEntity();
    if (emailLayout != null && emailVorgangDao.findByCountEmailLayout(emailLayout) > 0) {
      addErrorMessage("email.layout.edit.action.delete.not.possible.vorgang.message", emailLayout.getBezeichnung());
      return false;
    }
    if (emailLayout != null && emailVorlageDao.findByCountEmailLayout(emailLayout) > 0) {
      addErrorMessage("email.layout.edit.action.delete.not.possible.vorlage.message", emailLayout.getBezeichnung());
      return false;
    }
    return true;
  }
}
