package it.com.atlassian.stash.admin;

import com.atlassian.bitbucket.permission.Permission;
import com.atlassian.webdriver.bitbucket.element.PermissionKind;
import com.atlassian.webdriver.bitbucket.element.PermissionRow;
import com.atlassian.webdriver.bitbucket.page.admin.GlobalPermissionsPage;
import com.atlassian.webdriver.bitbucket.page.admin.UserEditPage;
import com.atlassian.webdriver.bitbucket.page.admin.UserListPage;
import it.com.atlassian.stash.BaseBrowserFuncTest;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertThat;

public class GlobalPermissionsDowngradeTest extends BaseBrowserFuncTest {

    private static final String USER = "testGPDF";
    private static final String PASSWORD = "password";

    @Before
    public void createUser() throws Exception {
        testContext.user(USER, USER, PASSWORD, "test@example.com");
    }

    @Test
    public void testDowngradeThroughRemovalOfDirectPermission() throws Exception {
        testContext.globalPermission(USER, Permission.ADMIN);

        GlobalPermissionsPage page = loginAs(USER, PASSWORD, GlobalPermissionsPage.class);

        // using remove button
        PermissionRow userItem = page.removeUserAndExpectError(USER);
        assertThat(userItem.getErrors(), hasItem("You cannot revoke this permission as it would downgrade your own permissions."));

        //reload
        page = BITBUCKET.visit(GlobalPermissionsPage.class);

        // using checkboxes
        userItem = page.getUserItem(USER);
        userItem.clickPermissionAndExpectError(PermissionKind.ADMIN);
        assertThat(userItem.getErrors(), hasItem("You cannot revoke this permission as it would downgrade your own permissions."));
    }

    @Test
    public void testDowngradeThroughRemovalOfGroup() {
        testContext.group("admin-group", USER).globalPermissionForGroup("admin-group", Permission.ADMIN);

        UserEditPage page = loginAs(USER, PASSWORD, UserListPage.class).setFilter(USER).getUser(USER).clickView();
        page.getGroups().remove("admin-group", true);
        assertThat(page.getAuiErrorMessages(), hasItem("You cannot remove yourself from this group as it would remove your own privilege."));
    }
}
