package com.prolog.eis.pallet_positioning;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public abstract class PositioningStrategy<ContainerInfoDto> {

    public int order;


    public List<ContainerInfoDto> sort(int order, List<ContainerInfoDto> list, BigDecimal qty, List<PositioningStrategy<ContainerInfoDto>> strategies) {
        if (this.order <= order) {
            list = sort(list, qty);
        }
        List<PositioningStrategy<ContainerInfoDto>> collect = strategies.stream().filter(x -> x.order > order).collect(Collectors.toList());
        if (collect.isEmpty()) {
            return list;
        }
        PositioningStrategy<ContainerInfoDto> positioningStrategy = getMinOrder(collect);
        if (Objects.nonNull(positioningStrategy)) {
            return positioningStrategy.sort(positioningStrategy.order, list, qty, strategies);
        }
        return list;
    }

    private PositioningStrategy<ContainerInfoDto> getMinOrder(List<PositioningStrategy<ContainerInfoDto>> collect) {
        int temp = collect.get(0).order;
        for (int i = 1; i < collect.size(); i++) {
            if (temp > collect.get(i).order) {
                temp = collect.get(i).order;
            }
        }
        final int new_temp = temp;
        List<PositioningStrategy<ContainerInfoDto>> collect1 = collect.stream().filter(x -> x.order == new_temp).collect(Collectors.toList());
        if (collect1.isEmpty()) {
            return null;
        }
        return collect1.get(0);
    }

    public int getOrder() {
        return order;
    }

    abstract public List<ContainerInfoDto> sort(List<ContainerInfoDto> list, BigDecimal qty);

}
