
package de.ivu.elect.business.kandidatur.boundary;

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

import de.ivu.elect.business.kandidatur.control.ListenkandidaturByRelativePositionComparator;
import de.ivu.elect.business.kandidatur.entity.Listenkandidatur;
import de.ivu.elect.business.wahlvorschlag.entity.Liste;

public class ListenkandidaturListenpositionResolver {

  public void updateListenpositionen(Liste liste, Listenkandidatur pivot) {
    List<Listenkandidatur> entities = new ArrayList<>(liste.getListenkandidaturen());

    incrementListenpositionen(entities, pivot);
    normalizeListenpositionen(entities);
  }

  public void updateListenpositionen(Liste liste) {
    normalizeListenpositionen(new ArrayList<>(liste.getListenkandidaturen()));
  }

  private void incrementListenpositionen(List<Listenkandidatur> entities, Listenkandidatur pivot) {
    long pivotPosition = pivot.getRelativePosition();

    for (Listenkandidatur entity : entities) {
      if (!entity.equals(pivot)) {
        long position = entity.getRelativePosition();

        if (position >= pivotPosition) {
          entity.setRelativePosition(position + 1);
        }
      }
    }
  }

  private void normalizeListenpositionen(List<Listenkandidatur> entities) {
    Collections.sort(entities, new ListenkandidaturByRelativePositionComparator());

    long position = 1;

    for (Listenkandidatur entity : entities) {
      entity.setRelativePosition(position);

      position++;
    }
  }
}
