
package de.ivu.elect.presentation.ui;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import javax.enterprise.inject.Specializes;
import javax.inject.Inject;

import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.business.security.control.ElectCommonPrincipal;
import de.ivu.elect.business.ui.boundary.UITableColumnOrderKonfiguration;
import de.ivu.elect.business.ui.boundary.UITableColumnReihenfolgeFestlegenEdit;
import de.ivu.elect.business.ui.entity.UITableColumnOrder;
import de.ivu.elect.business.wahl.boundary.WahlSessionSelector;
import de.ivu.elect.business.wahl.boundary.WahlterminSessionSelect;
import de.ivu.elect.jee.faces.FacesMessageUtil;
import de.ivu.elect.jee.presentation.dynamictable.ColumnBuilder;
import de.ivu.elect.jee.presentation.dynamictable.ColumnBuilderReorderEventListener;

@Specializes
public class ElectColumnBuilderReorderEventListener extends ColumnBuilderReorderEventListener {

  private static final long serialVersionUID = 1L;

  @Inject
  private transient ElectCommonPrincipal principal;

  @Inject
  private transient UITableColumnOrderKonfiguration uiTableColumnOrderKonfiguration;

  @Inject
  private transient UITableColumnReihenfolgeFestlegenEdit uiTableColumnReihenfolgeFestlegenEdit;

  @Inject
  private transient WahlSessionSelector wahlSessionSelector;

  @Inject
  private transient WahlterminSessionSelect wahlterminSessionSelect;

  public ElectColumnBuilderReorderEventListener() {
    super();
  }

  @Override
  public void onRowReorder(List<String> columnKeys, ColumnBuilder< ? > columnBuilder) {
    super.onRowReorder(columnKeys, columnBuilder);

    columnBuilder.forceInit();

    List<UITableColumnOrder> columnsVerfuegbar = uiTableColumnOrderKonfiguration.collectColumnsInColumnBuilderVerfuegbar(columnBuilder);

    List<UITableColumnOrder> columnsAngezeigt = uiTableColumnOrderKonfiguration.collectColumnsInColumnBuilderAngezeigt(columnBuilder).stream() //
        .sorted(Comparator.comparingInt(uiTableColumnOrder -> columnKeys.indexOf(uiTableColumnOrder.getColumnKey()))) //
        .collect(Collectors.toList());

    uiTableColumnReihenfolgeFestlegenEdit.save(principal, wahlSessionSelector.getEntity(), wahlterminSessionSelect.getEntity(), columnBuilder, columnsAngezeigt, columnsVerfuegbar);

    FacesMessageUtil.addInfoMessage("table.columns.reihenfolge.gespeichert");
  }

  public boolean isReihenfolgeAendernErlaubt() {
    return principal.hasUseCasePermission(UseCasePermission.UI_TABLE_COLUMN_EDIT);
  }
}
