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

import com.atlassian.webdriver.bitbucket.element.PullRequestTable;
import com.atlassian.webdriver.bitbucket.page.PullRequestListPage;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.List;

import static com.atlassian.bitbucket.pull.PullRequestState.DECLINED;
import static com.atlassian.bitbucket.util.Chainable.chain;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;

public class PullRequestListPagingTest extends BasePullRequestListFuncTest {

    private static final int PAGE_SIZE = 25;

    @Test
    public void testListPullRequestsPaging() {
        List<Long> ids = Lists.newArrayListWithCapacity(PAGE_SIZE * 2);

        for (int i = 0; i < PAGE_SIZE * 2; i++) {
            ids.add(createPullRequest(new PullRequestBuilder(BRANCH_THAT_HAS_SAME_FILE_MODIFIED_AND_MOVED_SRC,
                    BRANCH_THAT_HAS_SAME_FILE_MODIFIED_AND_MOVED_TRGT).build(), DECLINED).getId());
        }

        PullRequestListPage listPage = loginAs(AUTHOR_1, AUTHOR_1,
                PullRequestListPage.class, PROJECT_KEY, REPO_SLUG, ImmutableMap.builder()
                        .put("state", DECLINED.name())
                        .build());

        PullRequestTable pullRequestTable = listPage.getPullRequestTable();
        assertThat("There should be one page of pull request in the table of declined pull requests before scrolling",
                pullRequestTable.getRows().size(), equalTo(PAGE_SIZE));
        assertThat("There should be one more page to show before scrolling", not(listPage.isNoMoreResultsMessageVisible()));

        pullRequestTable.loadNextPage();
        assertThat("There should be two pages of pull request in the table of declined pull requests after scrolling",
                pullRequestTable.getRows().size(), equalTo(PAGE_SIZE * 2));
        assertThat("There should be no more pages to show after scrolling", listPage.isNoMoreResultsMessageVisible());

        List<Long> idsOnPage = pullRequestTable.getRows().stream()
                .map(PullRequestTable.Entry::getId)
                .collect(toList());

        assertThat("Ids out of order. Expected: " + ids + ". Actual: " + idsOnPage,
                Iterables.elementsEqual(Lists.reverse(ids), idsOnPage));
    }
}
