package it.com.atlassian.stash.admin;

import com.atlassian.bitbucket.test.LicenseTestHelper;
import com.atlassian.bitbucket.test.BitbucketTestLicense;
import com.atlassian.bitbucket.permission.Permission;
import com.atlassian.webdriver.bitbucket.page.admin.AdminHomePage;
import com.atlassian.webdriver.bitbucket.page.admin.GlobalPermissionsPage;
import it.com.atlassian.stash.BaseBrowserFuncTest;
import org.junit.*;

import java.io.UnsupportedEncodingException;

import static org.junit.Assert.assertFalse;

public class GlobalPermissionsPagingTest extends BaseBrowserFuncTest {

    public static final int PAGE_SIZE = 50;
    public static final int NUM_ITEMS = 2 * PAGE_SIZE;
    private static final BitbucketTestLicense FIVE_HUNDRED_USER_LICENSE = BitbucketTestLicense.builder()
            .whenClustered(
                    "AAABEg0ODAoPeNp9UF1Lw0AQfM+vOPA5JUmtH4UDtTlFSJpUU/F1jVt7kFzD3iaYf++ZXkFBhH2an\n" +
                            "Z2dmbN70iLFWsSJiOfLxdUyuRYPeSWSKD4PLIPdz9QATQ+sD0buoLHo4RXhBKbAKB09CaN5GC1O2\n" +
                            "4NhqHkNLcpKt6JEZiSLxu9z0IbRgKlRfXaaRi+TxGH0PZ7mJPSAkqnH38LKCTSSu5PsDXAD1mows\n" +
                            "/rQem6mazQWq7HDyUiqXlRWlOopeEYakB5TeVdkeTjfbFSYFkkWvl5uL/xxCcQGaTr0UEEfYLQ9d\n" +
                            "nF7eihKHkXG757kgsAKXTj6abvsqd6Dxb/b8kb/a2Ldt29IxW5rXV65iKLgC596lk0wLAIUPdlQZ\n" +
                            "O6BWwgz0iIPC/ggN1HNRCkCFERZIhK+emRlUctuc5kiclZivYF+X02dt")
            .whenNonClustered(
                    "AAABBw0ODAoPeNp9kE9vgzAMxe/9FJF2TpVQsU2VIu0POUyCQlc67eoxd40EASUGjW8/ysKhO0zy6\n" +
                            "fn552ffZK1lGTgmYibvtzLeSsn0oWSRkNHKE/jzWg9Q90CmteoEtccgPzucxQQI1cXOxYaLeOm2l\n" +
                            "qCiHTSoStOwAonQebShn4GxhBZshfq7M24MmEhycalgmxBmQEWux2uwngC1om7BPgDV4L0Bu67aJ\n" +
                            "nhTU6H1WI4dzkES/abTvNCvqwO6Ad1Lop7yNOOb/V7zJI9S/n53vA3DBTiy6ObBIOXuC6zxv794X\n" +
                            "BaygkaW0mcw7frmA11+OvopmIqFuA7z37VF76ozePz70h8PN44wMCwCFC5OHFL4zGBd27rmvFiL6\n" +
                            "LNX1YLpAhR2mDu6SHfZG9fE/708xtyjIQLqEw==X02dh")
            .build();

    private static String license;

    @BeforeClass
    public static void setUp() throws UnsupportedEncodingException {
        license = LicenseTestHelper.getLicense();
        LicenseTestHelper.setLicense(FIVE_HUNDRED_USER_LICENSE.get());

        for (int i = 0; i < NUM_ITEMS; i++) {
            String name = toPickerItemName(i);
            getClassTestContext()
                    .user(name)
                    .group(name);
        }
    }

    @AfterClass
    public static void restoreLicense() throws Throwable {
        if (license != null) {
            LicenseTestHelper.setLicense(license);
        }
    }

    @Before
    public void setUpPermissions() {
        for (int i = 0; i < NUM_ITEMS; i++) {
            String name = toPickerItemName(i);
            testContext.globalPermission(name, Permission.LICENSED_USER)
                    .globalPermissionForGroup(name, Permission.LICENSED_USER);
        }
    }

    @Test
    public void testUserPagingNotDisruptedByDeletes() throws Exception {
        testPagingNotDisruptedByDeletes(GlobalPermissionsPage.PermissionEntityType.USER);
    }

    @Test
    public void testGroupPagingNotDisruptedByDeletes() throws Exception {
        testPagingNotDisruptedByDeletes(GlobalPermissionsPage.PermissionEntityType.GROUP);
    }

    public void testPagingNotDisruptedByDeletes(GlobalPermissionsPage.PermissionEntityType entityType) throws InterruptedException, UnsupportedEncodingException {
        final GlobalPermissionsPage globalPermissions = loginAsAdmin(AdminHomePage.class).gotoGlobalPermissionsPage();

        //The first 10 users should be visible
        assertPresent(globalPermissions, entityType, 0, 10);

        //Remove 0th user
        globalPermissions.showAllRemoveButtons();
        globalPermissions.removeItem(entityType, toPickerItemName(0));

        //Load another page
        globalPermissions.loadMore(entityType);

        //1-19 should be showing
        assertFalse(globalPermissions.rowIsVisible(entityType, toPickerItemName(0)));
        assertPresent(globalPermissions, entityType, 1, 20);

        //Remove 15th group
        globalPermissions.showAllRemoveButtons();
        globalPermissions.removeItem(entityType, toPickerItemName(15));

        //Load another page
        globalPermissions.loadMore(entityType);

        //1-14 & 16-30 should be showing
        assertFalse(globalPermissions.rowIsVisible(entityType, toPickerItemName(0)));
        assertPresent(globalPermissions, entityType, 1, 15);
        assertFalse(globalPermissions.rowIsVisible(entityType, toPickerItemName(15)));
        assertPresent(globalPermissions, entityType, 16, 30);
    }

    public static void assertPresent(GlobalPermissionsPage globalPermissions, GlobalPermissionsPage.PermissionEntityType holder, int start, int end) {
        for (int i = start; i < end; i++) {
            assertPresent(globalPermissions, holder, i);
        }
    }

    private static void assertPresent(GlobalPermissionsPage globalPermissions, GlobalPermissionsPage.PermissionEntityType holder, int index) {
        Assert.assertTrue("Failed to find " + holder.singularName() + " row " + toPickerItemName(index), globalPermissions.getRow(holder, toPickerItemName(index)).isPresent());
    }

    public static String toPickerItemName(int i) {
        //left pad to keep item ordering stable
        return String.format("%02d", i);
    }
}
