package de.ivu.elect.presentation.dashboard;

import de.ivu.elect.business.konfiguration.entity.ElectKonfigurationWerte;
import de.ivu.elect.business.konfiguration.entity.KonfigurationExtendedLoader;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.business.security.control.ElectCommonPrincipal;
import de.ivu.elect.jee.faces.FacesContextUtil;
import de.ivu.elect.jee.faces.PreConditionCheck;
import de.ivu.elect.jee.presentation.view.AbstractView;
import de.ivu.elect.presentation.View;
import de.ivu.elect.presentation.dashboard.entries.AbstractDashboardEntry;
import de.ivu.elect.presentation.dashboard.entries.DashboardEntryBuilder;
import de.ivu.elect.presentation.hilfe.KeineOnlineHilfe;
import de.ivu.elect.presentation.hilfe.OnlineHilfeId;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.TabChangeEvent;

import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@RequestScoped
@Named(DashboardView.COMPONENT_NAME)
@View(viewId = DashboardView.VIEW_ID, useCase = UseCasePermission.DASHBOARD_ANZEIGEN)
@OnlineHilfeId(KeineOnlineHilfe.KEINE_ONLINE_HILFE)
public class DashboardView extends AbstractView {

  private static final long serialVersionUID = 1L;

  public static final String VIEW_ID = "/dashboard/dashboard.xhtml";

  public static final String COMPONENT_NAME = "dashboardView";

  @Inject
  private transient DashboardViewStore dashboardViewStore;

  @Inject
  private transient KonfigurationExtendedLoader konfigurationExtendedLoader;

  @Inject
  private transient ElectCommonPrincipal principal;

  @Inject
  private transient DashboardEntryBuilder dashboardEntryBuilder;

  @Inject
  private transient DashboardActiveTabSelect dashboardActiveTabSelect;

  @Inject
  private transient DashboardRedirectCheck dashboardRedirectCheck;


  @PreConditionCheck
  public String checkPrecondition() {
    return dashboardRedirectCheck.checkDashboardRedirect();
  }

  List<AbstractDashboardEntry> fieldSets = null;

  public List<AbstractDashboardEntry> getFieldsets() {
    if (fieldSets == null) {
      fieldSets = dashboardEntryBuilder.getEntries().stream().filter(AbstractDashboardEntry::isRendered).collect(Collectors.toList());
    }
    return fieldSets;
  }

  public String getFieldIds() {
    return getFieldsets().stream().map(AbstractDashboardEntry::getId).collect(Collectors.joining(","));
  }


  public String getWelcomeHeader() {
    return konfigurationExtendedLoader.resolveStringValue(ElectKonfigurationWerte.DASHBOARD_NEWS_HEADER);
  }

  public String getWelcomeMsg() {
    return konfigurationExtendedLoader.resolveStringValue(ElectKonfigurationWerte.DASHBOARD_NEWS_MESSAGE_SNIPPET);
  }

  public boolean isWelcomMsgVisible() {
    return dashboardViewStore.isWelcomeMsgVisible();
  }

  public void welcomeMsgClose() {
    dashboardViewStore.setWelcomeMsgVisible(false);
  }

  public boolean isWelcomMsgRendered() {
    return StringUtils.isNotBlank(getWelcomeMsg()) && StringUtils.isNotBlank(getWelcomeHeader()) && principal
            .hasUseCasePermission(UseCasePermission.DASHBOARD_NEWS_ANZEIGEN);
  }

  public Boolean isFocused(AbstractDashboardEntry abstractDashboardEntry) {
    return getFieldsets().indexOf(abstractDashboardEntry) == 0;
  }

  public int getActiveIndex() {

    if (!FacesContextUtil.isAjaxRequest() && FacesContext.getCurrentInstance().isPostback()) {
      // Bei POST nicht beachten
      return 0;
    }

    if (StringUtils.isBlank(dashboardActiveTabSelect.getActiveTabId()) ||
        getFieldsets().stream().filter(d -> dashboardActiveTabSelect.getActiveTabId().equals(d.getId())).noneMatch(AbstractDashboardEntry::isEingabeErwartet)) {
      // erstes Feld mit erwarter Eingabe anzeigen und merken
      getFieldsets().stream().filter(AbstractDashboardEntry::isEingabeErwartet).findFirst()
          .ifPresent(fieldset -> dashboardActiveTabSelect.setActiveTabId(fieldset.getId()));
    }

    if (StringUtils.isNotBlank(dashboardActiveTabSelect.getActiveTabId())) {
      return getFieldsets().stream().filter(fieldset -> dashboardActiveTabSelect.getActiveTabId().equals(fieldset.getId())).findFirst().map(fieldset -> getFieldsets().indexOf(fieldset)).orElse(0);
    }

    return 0;
  }

  public void setActiveIndex(int index) {
    // ignorieren
  }

  public void onTabChange(TabChangeEvent event) {
    dashboardActiveTabSelect.setActiveTabId(event.getTab().getId());
  }

  public List<String> getAfterTemplates(){
    return getFieldsets().stream()
        .map(AbstractDashboardEntry::getAfterTemplates)
        .flatMap(Collection::stream)
        .collect(Collectors.toList());
  }
}


