package it.com.atlassian.stash.rest.pull;

import com.atlassian.bitbucket.permission.Permission;
import com.atlassian.bitbucket.test.DefaultFuncTestData;
import org.junit.Before;
import org.junit.BeforeClass;

import java.util.Map;

public abstract class BasePullRequestParticipantResourceTest extends BasePullRequestResourceTest {

    protected static final String PR_PARTICIPANT_TEST = "prparticipanttest";
    protected static final String PROJ_WRITER = PR_PARTICIPANT_TEST + "_writer";
    protected static final String AUTHOR = PR_PARTICIPANT_TEST + "_author";
    protected static final String REVIEWER = PR_PARTICIPANT_TEST + "_reviewer";
    protected static final String REVIEWER2 = PR_PARTICIPANT_TEST + "_reviewer2";
    protected static final String USER_WITHOUT_PERMISSION = PR_PARTICIPANT_TEST + "_user_without_permission";

    @BeforeClass
    public static void setup() throws Exception {
        getClassTestContext()
                .project(PR_PARTICIPANT_TEST)
                .repository(PR_PARTICIPANT_TEST, PR_PARTICIPANT_TEST, REPO_ZIP)
                .user(PROJ_WRITER).projectPermission(PR_PARTICIPANT_TEST, PROJ_WRITER, Permission.PROJECT_WRITE)
                .user(AUTHOR).projectPermission(PR_PARTICIPANT_TEST, AUTHOR, Permission.PROJECT_READ)
                .user(REVIEWER).projectPermission(PR_PARTICIPANT_TEST, REVIEWER, Permission.PROJECT_READ)
                .user(REVIEWER2).projectPermission(PR_PARTICIPANT_TEST, REVIEWER2, Permission.PROJECT_READ)
                .user(USER_WITHOUT_PERMISSION);
    }

    @Before
    public void setupPullRequest() {
        pullRequest = createPullRequest(testContext, AUTHOR, PR_PARTICIPANT_TEST);
        pullRequest.addReviewers(REVIEWER, REVIEWER2);
    }

    protected String getUrl(String projectKey, String repoSlug, Map<String, String> queryParameters) {
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, String> parameter : queryParameters.entrySet()) {
            // No need to URL encode these. RestAssured will take care of it.
            builder.append(builder.length() == 0 ? "?" : "&")
                    .append(String.format("%s=%s", parameter.getKey(), parameter.getValue()));
        }

        return getUrl(projectKey, repoSlug) + builder.toString();
    }

    protected String getUrl(String projectKey, String repoSlug) {
        return DefaultFuncTestData.getRestURL() + "/projects/" + projectKey + "/repos/" + repoSlug + "/participants";
    }
}
