package com.atlassian.stash.internal.task;

import com.atlassian.bitbucket.task.TaskAnchorType;
import com.atlassian.fugue.Effect;
import com.atlassian.stash.internal.comment.InternalComment;

import javax.annotation.Nonnull;

import static com.google.common.collect.Iterables.partition;

class TaskDaoUtils {

    /**
     * Execute an {@link Effect} against an {@link Iterable} in batches. This allows the stream-like behaviour
     * while using the core Java Iterable API. A typical use case is where an iterable will eventually be
     * unrolled into a collection or list and we want guarantee the maximum number of elements retrieved at
     * any one time.
     *
     * @param iterable the iterable that will be batched
     * @param batchSize the number of elements in each batch. The last batch may have fewer than this number
     *                  of elements.
     * @param f the effect to run against each batch
     */
    public static <T> void executeAsBatch(@Nonnull Iterable<T> iterable, int batchSize, @Nonnull Effect<Iterable<T>> f) {
        for (Iterable<T> batch : partition(iterable, batchSize)) {
            f.apply(batch);
        }
    }

    /**
     * Converts a {@link TaskAnchorType anchorType} to its discriminator class name value
     * used by hibernate.
     *
     * @param anchorType the anchor type to be converted
     * @return the class name of the class implementing the anchorType
     */
    public static String convertToClassName(com.atlassian.bitbucket.task.TaskAnchorType anchorType) {
        switch (anchorType) {
            case COMMENT:
                return InternalComment.class.getName();
            default:
                throw new IllegalStateException("Unsupported TaskAnchorType: " + anchorType);
        }
    }

}
