package com.atlassian.bitbucket.pull;

import com.atlassian.bitbucket.task.Task;
import com.atlassian.bitbucket.task.TaskAnchor;
import com.atlassian.bitbucket.util.PageRequest;
import com.google.common.collect.ImmutableSet;

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

/**
 * Request for searching a pull request's {@link Task tasks}.
 *
 * @see PullRequestService#searchTasks(PullRequestTaskSearchRequest, PageRequest)
 * @see PullRequestService#countTasks(PullRequestTaskSearchRequest)
 */
public class PullRequestTaskSearchRequest extends AbstractPullRequestRequest {

    private final Set<Long> anchorIds;
    private final PullRequest pullRequest;

    private PullRequestTaskSearchRequest(Builder builder) {
        super(builder);

        anchorIds = builder.anchorIds.build();
        pullRequest = builder.pullRequest;
    }

    /**
     * Limit the search to the specified {@link TaskAnchor task anchorIds}
     *
     * @return the task anchorIds that limit the search or an empty set if the search shouldn't be limited
     */
    @Nonnull
    public Set<Long> getAnchorIds() {
        return anchorIds;
    }

    /**
     * @return the pull request that limits the search
     */
    @Nullable
    public PullRequest getPullRequest() {
        return pullRequest;
    }

    /**
     * @return {@code true} if this search request has a {@link PullRequest pullRequest} object
     */
    public boolean hasPullRequest() {
        return pullRequest != null;
    }

    public static class Builder extends AbstractBuilder<Builder> {

        private final ImmutableSet.Builder<Long> anchorIds = ImmutableSet.builder();

        private PullRequest pullRequest;

        public Builder(@Nonnull PullRequest pullRequest) {
            super(pullRequest);

            this.pullRequest = pullRequest;
        }

        public Builder(int repositoryId, long pullRequestId) {
            super(repositoryId, pullRequestId);
        }

        @Nonnull
        public Builder anchor(long value) {
            anchorIds.add(value);

            return self();
        }

        @Nonnull
        public Builder anchors(@Nullable Iterable<Long> value) {
            addIf(Objects::nonNull, anchorIds, value);

            return self();
        }

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

        @Nonnull
        @Override
        protected Builder self() {
            return this;
        }
    }
}
