package com.atlassian.stash.internal.task;

import com.atlassian.bitbucket.task.*;
import com.atlassian.bitbucket.task.TaskAnchorType;
import com.atlassian.bitbucket.util.BuilderSupport;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

import static com.google.common.base.Preconditions.checkNotNull;

public class InternalTaskSearchRequest {

    private final Set<Long> anchorIds;
    private final com.atlassian.bitbucket.task.TaskAnchorType anchorType;
    private final InternalTaskContext context;

    private InternalTaskSearchRequest(Builder builder) {
        this.anchorIds = builder.anchorIds;
        this.anchorType = builder.anchorType;
        this.context = builder.context;
    }

    /**
     * Limits the returned {@link Task tasks} to only those which match the specified
     * anchor ids.
     *
     * @return the IDs of the anchors for the tasks
     * @see TaskAnchor
     */
    @Nonnull
    public Set<Long> getAnchorIds() {
        return anchorIds;
    }


    /**
     * Limits the returned {@link Task tasks} to only those which match the specified
     * anchor type.
     *
     * @return the required anchor type for the tasks, or {@code null} to return tasks regardless of anchor type.
     * @see TaskAnchor
     */
    @Nullable
    public TaskAnchorType getAnchorType() {
        return anchorType;
    }

    /**
     * Limits the returned {@link Task tasks} to only those which match the specified
     * {@link InternalTaskContext context}.
     *
     * @return the context the tasks
     */
    @Nonnull
    public InternalTaskContext getContext() {
        return context;
    }

    public static class Builder extends BuilderSupport {

        private final Set<Long> anchorIds = new HashSet<>();
        private TaskAnchorType anchorType;
        private InternalTaskContext context;

        public Builder(@Nonnull InternalTaskContext context) {
            this.context = checkNotNull(context, "context");
        }

        @Nonnull
        public InternalTaskSearchRequest build() {
            return new InternalTaskSearchRequest(this);
        }

        @Nonnull
        public Builder anchors(@Nonnull Iterable<Long> anchorIds, @Nonnull TaskAnchorType anchorType) {
            addIf(Objects::nonNull, this.anchorIds, anchorIds);

            this.anchorType = checkNotNull(anchorType, "anchorType");

            return this;
        }

    }
}