package com.prolog.eis.roadway_allocation;

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

public abstract class AllocationStrategy<T> {

    public Integer order;

    public List<T> sort(int order, List<T> list, List<AllocationStrategy<T>> strategies) {
        if (this.order <= order) {
            list = sort(list);
        }
        List<AllocationStrategy<T>> collect = strategies.stream().filter(x -> x.order > order).collect(Collectors.toList());
        if (collect.isEmpty()) {
            return list;
        }
        AllocationStrategy<T> allocationStrategy = getMinOrder(collect);
        if (Objects.nonNull(allocationStrategy)) {
            return allocationStrategy.sort(allocationStrategy.order, list, strategies);
        }
        return list;
    }

    private AllocationStrategy<T> getMinOrder(List<AllocationStrategy<T>> collect) {
        int temp;
        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<AllocationStrategy<T>> collect1 = collect.stream().filter(x -> x.order == new_temp).collect(Collectors.toList());
        if (collect1.isEmpty()) {
            return null;
        }
        return collect1.get(0);
    }

    public Integer getOrder() {
        return order;
    }

    abstract public List<T> sort(List<T> list);
}
