
package de.ivu.elect.presentation.email;

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

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

import de.ivu.elect.business.email.entity.EmailVorlage;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.business.wahl.boundary.WahlterminNichtAusgewaehltException;
import de.ivu.elect.jee.entity.EagerLoadingCollector;
import de.ivu.elect.jee.faces.PreConditionCheck;
import de.ivu.elect.jee.presentation.dynamicform.FormBuilder;
import de.ivu.elect.jee.presentation.search.AbstractSearchParameters;
import de.ivu.elect.presentation.View;
import de.ivu.elect.presentation.email.table.EmailVorlageColumnBuilder;
import de.ivu.elect.presentation.hilfe.OnlineHilfeId;
import de.ivu.elect.presentation.security.AbstractGebietSecurityFilter;

@OnlineHilfeId("736")
@ViewAccessScoped
@Named(AbstractEmailVorlageSearchView.COMPONENT_NAME)
@View(viewId = AbstractEmailVorlageSearchView.VIEW_ID, useCase = UseCasePermission.EMAIL_VORLAGE_SEARCH)
public class EmailVorlageSearchView extends AbstractEmailVorlageSearchView {

  private static final long serialVersionUID = 1L;

  @Inject
  private transient EmailLayoutUiVisibility emailLayoutUiVisibility;

  @Inject
  private transient EmailVorlageColumnBuilder emailVorlageColumnBuilder;

  private Boolean emailLayoutsVisible = null;

  public EmailVorlageSearchView() {
    super();
  }

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

    return null;
  }

  @Override
  protected AbstractGebietSecurityFilter<EmailVorlage> getGebietSecurityFilter() {
    return KEIN_GEBIET_SECURITY_FILTER;
  }

  @Override
  public void presetSearchParameters() {
    // Do nothing...
  }

  @Override
  public void addProperties(FormBuilder formBuilder) {
    checkPreCondition();

    String wildcardTooltip = getMessage(AbstractSearchParameters.WILDCARD_TOOLTIP_MSG_KEY);

    formBuilder.addProperty(getSearchParameters().getBezeichnungProperty()).withTooltip(wildcardTooltip).withRequired(false);

    if (isEmailLayoutSearchParameterVisible()) {
      formBuilder.addProperty(getSearchParameters().getEmailLayoutProperty()).withRequired(false);
    }
  }

  private boolean isEmailLayoutSearchParameterVisible() {
    if (emailLayoutsVisible == null) {
      emailLayoutsVisible = emailLayoutUiVisibility.isEmailLayoutAuswahlVisible();
    }

    return emailLayoutsVisible;
  }

  @Override // ELECTKOM-1649
  public EagerLoadingCollector<EmailVorlage> getEagerLoadingCollector() {
    EagerLoadingCollector<EmailVorlage> eagerLoadingCollector = EagerLoadingCollector.create();
    emailVorlageColumnBuilder.collectEagerLoadings(eagerLoadingCollector);

    return eagerLoadingCollector;
  }
}
