/*
 * Copyright (c) 2022 MiLaboratories Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.milaboratory.util;

import java.util.Arrays;
import java.util.List;

/**
 * Accumulator to select bottom N element for a stream of objects.
 * Uses natural ordering of objects and selects N smallest elements.
 */
public final class BottomN<T extends Comparable<T>> {
    private int len;
    private final Object[] elements;

    public BottomN(int n) {
        this.elements = new Object[n];
    }

    public void add(T e) {
        int i = Arrays.binarySearch(elements, 0, len, e);
        if (len < elements.length) {
            if (i < 0)
                i = -1 - i;
            System.arraycopy(elements, i, elements, i + 1, len - i);
            len++;
        } else {
            if (i == len - 1 || i == -1 - len)
                // All elements in array are smaller or equal than e
                return;
            if (i < 0)
                i = -1 - i;
            System.arraycopy(elements, i, elements, i + 1, len - i - 1);
        }
        elements[i] = e;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public List<T> result() {
        if (len < elements.length)
            return (List) Arrays.asList(Arrays.copyOf(elements, len));
        else
            return (List) Arrays.asList(elements);
    }
}
