
package de.ivu.elect.presentation.geodata.table;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import de.ivu.elect.business.geodata.control.GeodataPlzByPlzComparator;
import de.ivu.elect.business.geodata.entity.GeodataOrt;
import de.ivu.elect.business.geodata.entity.GeodataOrtMeta;
import de.ivu.elect.business.geodata.entity.GeodataPlz;
import de.ivu.elect.business.geodata.entity.GeodataPlzConstants;
import de.ivu.elect.jee.faces.Messages;
import de.ivu.elect.jee.presentation.dynamictable.ColumnType;


import static java.util.Objects.nonNull;

public class GeodataOrtGeodataPlzColumn<E extends GeodataOrt> extends AbstractGeodataOrtColumn<E> {

  private static final long serialVersionUID = 1L;

  private static final Comparator<GeodataPlz> DEFAULT_COMPARATOR = new GeodataPlzByPlzComparator();

  private static final int MAX_ITEM_COUNT = 10;

  protected GeodataOrtGeodataPlzColumn(Messages messages, GeodataOrtMeta geodataOrtMeta) {
    super(messages, GeodataPlzConstants.MESSAGE_KEY_ENTITY_MEHRZAHL, ColumnType.COLLECTION, geodataOrt -> {
      List<String> result = new ArrayList<>();

      if (nonNull(geodataOrt)) {
        List<GeodataPlz> geodataPostleitzahlen = new ArrayList<>(geodataOrt.getGeodataPostleitzahlen());

        Collections.sort(geodataPostleitzahlen, DEFAULT_COMPARATOR);

        int geodataPostleitzahlenCount = geodataPostleitzahlen.size();
        int geodataPostleitzahlenSkippedCount = geodataPostleitzahlenCount - MAX_ITEM_COUNT;

        for (int i = 0; i < Math.min(geodataPostleitzahlenCount, MAX_ITEM_COUNT); i++) {
          result.add(geodataPostleitzahlen.get(i).getPlz());
        }

        if (geodataPostleitzahlenSkippedCount > 0) {
          result.add(messages.getMessageForMessageKey("column.value.items.count.skipped", geodataPostleitzahlenSkippedCount));
        }
      }

      return result;
    });
  }

}
