package com.atlassian.bitbucket.util;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

public class PageUtilsTest {

    @Test
    public void testNewRequestWithoutFilter() throws Exception {
        PageRequest request = PageUtils.newRequest(1, 5);
        assertEquals(1, request.getStart());
        assertEquals(5, request.getLimit());
    }

    @Test
    public void testReducePage() throws Exception {
        List<Integer> list = Arrays.asList(10, 42, 34, 15);
        PageRequest request = PageUtils.newRequest(0, 4);
        Page<Integer> page = new PageImpl<Integer>(request, list, true);

        Page<Integer> actual = PageUtils.reducePage(page, 2, request);
        assertEquals(0, actual.getStart());
        assertEquals(2, actual.getLimit());
        assertEquals(2, actual.getSize());
        assertEquals(2, Iterables.size(actual.getValues()));
        assertEquals(10, (int) Iterables.get(actual.getValues(), 0));
        assertEquals(42, (int) Iterables.get(actual.getValues(), 1));
        assertFalse(actual.getIsLastPage());

        // same size as the original page
        actual = PageUtils.reducePage(page, list.size(), request);
        assertEquals(0, actual.getStart());
        assertEquals(list.size(), actual.getLimit());
        assertEquals(list.size(), actual.getSize());
        assertEquals(list.size(), Iterables.size(actual.getValues()));
        assertEquals(Lists.newArrayList(list), Lists.newArrayList(actual.getValues()));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testReduceLarger() throws Exception {
        PageRequest request = PageUtils.newRequest(0, 2);
        Page<Integer> page = new PageImpl<Integer>(request, Arrays.asList(12, 23), true);
        PageUtils.reducePage(page, 5, request);
    }
}
