
package de.ivu.elect.presentation.ui;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

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

import de.ivu.elect.business.security.control.ElectCommonPrincipal;
import de.ivu.elect.business.ui.boundary.UITableColumnOrderExtendedDAO;
import de.ivu.elect.business.ui.boundary.UITableColumnOrderKonfiguration;
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.presentation.dynamictable.AbstractColumnBuilder;
import de.ivu.elect.jee.presentation.dynamictable.ColumnEntry;
import de.ivu.elect.jee.presentation.dynamictable.ColumnFilter;

@Specializes
public class ElectColumnFilter extends ColumnFilter {

  private static final long serialVersionUID = 1L;

  @Inject
  private transient ElectCommonPrincipal principal;

  @Inject
  private transient UITableColumnOrderExtendedDAO uiTableColumnOrderExtendedDAO;

  @Inject
  private transient UITableColumnOrderKonfiguration uiTableColumnOrderKonfiguration;

  @Inject
  private transient WahlSessionSelector wahlSessionSelector;

  @Inject
  private transient WahlterminSessionSelect wahlterminSessionSelect;

  public ElectColumnFilter() {
    super();
  }

  @Override
  public <E> List<ColumnEntry< ? super E>> filter(List<ColumnEntry< ? super E>> columnEntries, AbstractColumnBuilder<E> columnBuilder) {
    List<ColumnEntry< ? super E>> columnsInColumnBuilder = new ArrayList<>(super.filter(columnEntries, columnBuilder));

    List<UITableColumnOrder> columnsInDb = uiTableColumnOrderKonfiguration.collectColumnsInDb(principal, wahlSessionSelector.getEntity(), wahlterminSessionSelect.getEntity(), columnBuilder,
        uiTableColumnOrderExtendedDAO);
    Map<String, UITableColumnOrder> columnInDbPerColumnKey = columnsInDb.stream().collect(toMap(UITableColumnOrder::getColumnKey, Function.identity()));

    if (columnsInDb.isEmpty()) {
      return columnsInColumnBuilder;
    }

    List<ColumnEntry< ? super E>> result = columnsInColumnBuilder.stream() //
        .filter(columnEntry -> uiTableColumnOrderKonfiguration.isColumnAnzuzeigen(columnInDbPerColumnKey, columnEntry)) //
        .collect(toList());

    Collections.sort(result, new ColumnEntryByUITableColumnOrderComparator(columnInDbPerColumnKey));

    return result;
  }
}
