package com.atlassian.stash.internal.plugin.hooks.task;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.pull.PullRequest;
import com.atlassian.bitbucket.pull.PullRequestService;
import com.atlassian.bitbucket.pull.PullRequestTaskSearchRequest;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.pull.MergeRequest;
import com.atlassian.bitbucket.scm.pull.MergeRequestCheck;
import com.atlassian.bitbucket.task.TaskCount;
import com.atlassian.bitbucket.task.TaskState;

import javax.annotation.Nonnull;

/**
 * Vetoes any pull request that has unresolved tasks.
 *
 * @see IncompleteTasksMergeCheckConfig
 */
public class IncompleteTasksMergeCheck implements MergeRequestCheck {

    private final I18nService i18nService;
    private final IncompleteTasksMergeCheckConfig config;
    private final PullRequestService pullRequestService;

    public IncompleteTasksMergeCheck(I18nService i18nService, IncompleteTasksMergeCheckConfig config,
            PullRequestService pullRequestService) {
        this.config = config;
        this.i18nService = i18nService;
        this.pullRequestService = pullRequestService;
    }

    @Override
    public void check(@Nonnull MergeRequest mergeRequest) {
        PullRequest pullRequest = mergeRequest.getPullRequest();
        Repository repository = pullRequest.getToRef().getRepository();

        if (config.isResolutionRequired(repository)) {
            TaskCount count = pullRequestService.countTasks(new PullRequestTaskSearchRequest.Builder(pullRequest).build());

            if (count.getCount(TaskState.OPEN) > 0) {
                mergeRequest.veto(i18nService.getMessage("bitbucket.pull.task.resolved.label"),
                        i18nService.getMessage("bitbucket.pull.task.resolved.message"));
            }
        }
    }

}
