package old.page;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.util.List;

/**
 * @author kote
 */
public class AdminRolePage extends BaseComponentPage {

  private static final String CELL_WITH_ROLE_NAME = "//div[@col-id='role$name']//span[contains(text(),'%s')]";
  private static final String LINK_GROUP_TABLE = "//*[@object-name='GroupsGrid']";
  private static final String ROLE_NAME_TABLE = "//*[@object-name='Grid']";

  private static final By LINKED_GROUP_GRID = By.xpath(LINK_GROUP_TABLE + "//div[@col-id='group$name']" + EXCLUDE_HEADER);
  private static final By ROLE_NAMES_GRID = By.xpath(ROLE_NAME_TABLE + "//div[@col-id='role$name']" + EXCLUDE_HEADER);
  private static final By LINKED_GROUP_GRID_HEADER = By.xpath(LINK_GROUP_TABLE + "//div[@col-id='group$name']" + AG_HEADER);
  private static final By ROLE_NAMES_GRID_HEADER = By.xpath(ROLE_NAME_TABLE + "//div[@col-id='role$name']" + AG_HEADER);

  public AdminRolePage(WebDriver browser) {
    super(browser, "/#/");
  }

  public void searchRole(String roleName) {
    waitProgressBarNotVisible();
    waitForVisibilityOf(searchField);
    typeTextOnAdminFilter(searchField, roleName);
    waitForInvisibilityGridDownloader();
    waitForPageLoad();
  }

  public void chooseRole(String roleName) {
    searchRole(roleName);
    getListOfRolesNamesFromTable(roleName).get(0).click();
    waitForInvisibilityGridDownloader();
  }

  public void deleteRole() {
    waitProgressBarNotVisible();
    clickDeleteButton();
    clickConfirmButton();
    waitProgressBarNotVisible();
  }

  public List<WebElement> getListOfRolesNamesFromTable(String name) {
    return driver.findElements(By.xpath(String.format(CELL_WITH_ROLE_NAME, name)));
  }

  public List<WebElement> getListOfRoleLinkedGroups() {
    return driver.findElements(LINKED_GROUP_GRID);
  }

  public List<WebElement> getListOfRoles() {
    return driver.findElements(ROLE_NAMES_GRID);
  }

  public void changeRolePageGridSort(RolePageGrids value) {
    switch (value) {
      case GROUP_NAMES_GRID:
        driver.findElement(LINKED_GROUP_GRID_HEADER).click();
        break;
      case ROLE_NAMES_GRID:
        driver.findElement(ROLE_NAMES_GRID_HEADER).click();
        break;
    }
    waitForPageLoad();
  }

  public enum RolePageGrids {
    ROLE_NAMES_GRID,
    GROUP_NAMES_GRID
  }
}