
package de.ivu.elect.presentation.wahl;

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

import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.business.security.UseCaseSecure;
import de.ivu.elect.business.wahl.boundary.WahlterminSessionSelect;
import de.ivu.elect.business.wahl.entity.Wahltermin;
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.hilfe.OnlineHilfeId;
import de.ivu.elect.presentation.wahl.form.WahlterminViewFormBuilder;

@OnlineHilfeId("434")
@Named(AbstractWahlterminEditView.COMPONENT_NAME)
public class WahlterminEditView extends AbstractWahlterminEditView {

  private static final long serialVersionUID = 1L;

  @Inject
  private transient WahlterminSessionSelect wahlterminSelect;

  @Inject
  private transient WahlterminViewFormBuilder viewFormBuilder;

  public WahlterminEditView() {
    super();
  }

  @Override
  @PreConditionCheck
  public String checkPreCondition() {
    if (getEntity() == null) {
      return cancel();
    }

    return null;
  }

  @Override
  public void addProperties(FormBuilder formBuilder, Wahltermin wahltermin) {
    viewFormBuilder.addProperties(formBuilder, wahltermin);
  }

  @Override
  @Redirect
  @UseCaseSecure(UseCasePermission.WAHLTERMIN_DELETE)
  public String delete() {
    Wahltermin wahltermin = getEntity();

    boolean currentlySessionSelectedWahltermin = isCurrentlySessionSelectedWahltermin();

    String delete = super.delete(wahltermin);
    if (currentlySessionSelectedWahltermin) {
      clearWahlterminSelect(); // nur im Erfolgsfall ausführen vgl. ELECTVAPP-1959
    }
    return delete;
  }

  private boolean isCurrentlySessionSelectedWahltermin() {
    return wahlterminSelect.isSelected() && wahlterminSelect.getEntity().equals(getEntity());
  }

  private void clearWahlterminSelect() {
    wahlterminSelect.setEntity((Wahltermin) null);
  }

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