package com.atlassian.webdriver.bitbucket.page.admin;

import com.atlassian.pageobjects.elements.ElementBy;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.query.Poller;
import com.atlassian.webdriver.bitbucket.element.GroupDeleteDialog;
import com.atlassian.webdriver.bitbucket.element.GroupUsersTable;
import com.atlassian.webdriver.bitbucket.page.BitbucketPage;
import org.openqa.selenium.By;

public class GroupEditPage extends BitbucketPage {

    @ElementBy(id = "groups-link")
    private PageElement groupsLink;
    @ElementBy(id = "group-name")
    private PageElement groupName;

    @ElementBy(id = "delete-group")
    PageElement deleteGroup;

    public String getUrl() {
        return "/admin/groups/view";
    }

    public Object getName() {
        return groupName.getText();
    }

    public GroupListPage clickGroupsLink() {
        return clickAndBind(groupsLink, GroupListPage.class);
    }

    public GroupDeleteDialog clickDelete() {
        deleteGroup.click();
        return getDialog();
    }

    private GroupDeleteDialog getDialog() {
        GroupDeleteDialog dialog = body.find(By.id(GroupDeleteDialog.ID), GroupDeleteDialog.class);
        Poller.waitUntilTrue(dialog.timed().isVisible());
        return dialog;
    }

    public GroupUsersTable getUsers() {
        return pageBinder.bind(GroupUsersTable.class, elementFinder.find(By.id("group-users-table")));
    }

    private <P extends BitbucketPage> P clickAndBind(PageElement element, Class<P> page) {
        element.click();
        return pageBinder.bind(page);
    }

}
