package nextflow.k8s.strategies

import groovy.transform.CompileStatic
import nextflow.k8s.K8sSchedulingDecision
import nextflow.k8s.K8sSchedulingRequest
import nextflow.k8s.K8sSchedulingStrategy
import nextflow.k8s.K8sTaskScheduler

@CompileStatic
class K8sHashSchedulingStrategy implements K8sSchedulingStrategy {

    @Override
    K8sSchedulingDecision schedule(K8sTaskScheduler scheduler, List<K8sSchedulingRequest> queue) {
        if (!queue)
            return null

        final freeNodes = scheduler.freeNodes
        if (freeNodes.size() == 0)
            return null

        final request = queue[0]
        final index = Math.floorMod(request.task.hash.asInt(), freeNodes.size())
        return new K8sSchedulingDecision(request, freeNodes[index])
    }

    @Override
    boolean scheduleImmediately(K8sTaskScheduler scheduler, List<K8sSchedulingRequest> queue) {
        if (!queue)
            return false
        final freeNodes = scheduler.freeNodes
        return freeNodes.size() > 0
    }
}
