package com.brilliance.isc.common.taskdistributor.util;

import org.redisson.RedissonPriorityQueue;
import org.redisson.api.RPriorityQueue;

import java.util.Objects;
import java.util.function.Function;

public class TaskPoolUtils {

    public static <T, I> void removeByInr(RPriorityQueue<T> pool, Function<T, I> inrGetter, I inr) {
        int index = -1;
        int i = 0;
        for (T t : pool) {
            if (Objects.equals(inrGetter.apply(t), inr)) {
                index = i;
                break;
            }
            i++;
        }
        if (index >= 0) {
            ((RedissonPriorityQueue<T>)pool).remove(index);
        }
    }

    public static <T, I> void putIfAbsent(RPriorityQueue<T> pool, T obj, Function<T, I> idIndicator) {
        if (!exists(pool, obj, idIndicator)) {
            pool.offer(obj);
        }
    }

    public static <T, I> boolean exists(RPriorityQueue<T> pool, T obj, Function<T, I> idIndicator) {
        int index = -1;
        int i = 0;
        for (T t : pool) {
            if (Objects.equals(idIndicator.apply(t), idIndicator.apply(obj))) {
                index = i;
                break;
            }
            i++;
        }
        return index >= 0;
    }

}
