package pages;

import java.util.List;

import core.BasePage;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

/**
 * @author kote
 */
public class RolesPage extends BasePage {

  private static final String TEXT_ON_PAGE = "//text//div[contains(.,'%s')]";
  private static final String ROLES_GRID = "//in-memory-static-column-grid[@object-name='Grid']";
  private static final String GROUPS_GRID = "//in-memory-static-column-grid[@object-name='GroupsGrid']";
  private static final String ROWS = "//div[@role='row'][not(contains(@class,'ag-header'))]";
  private static final String ROLES_ROWS = ROLES_GRID + ROWS;
  private static final String GROUPS_ROWS = GROUPS_GRID + ROWS;
  private static final String ROLES_ROW_BY_TEXT = ROLES_GRID + "//div[@role='row'][.//span[contains(.,'%s')]]";
  private static final String GROUPS_ROW_BY_TEXT = GROUPS_GRID + "//div[@role='row'][.//span[contains(.,'%s')]]";
  private static final String ROLES_NAMES_CELLS = ROLES_GRID + "//div[@col-id='role$name'][not(contains(@class,'ag-header'))]";
  private static final String ROLES_NAME_COLUMN_HEADER = ROLES_GRID + "//div[@col-id='role$name'][contains(@class,'ag-header')]";

  @FindBy(xpath = "//div[label[span[contains(.,'Наименование')]]]//input")
  private WebElement roleName;
  @FindBy(xpath = "//*[@object-name='search']//input")
  private WebElement searchField;

  public RolesPage(WebDriver browser) {
    super(browser, "/#/user-management/roles");
  }

  public boolean isTitleVisible(String title) {
    return isPresent(getBy(TEXT_ON_PAGE, title));
  }

  public boolean isRoleVisible(String name) {
    return isPresent(getBy(ROLES_ROW_BY_TEXT, name));
  }

  public boolean isGroupVisible(String name) {
    return isPresent(getBy(GROUPS_ROW_BY_TEXT, name));
  }

  public void clickOnRole(String name) {
    waitForElementToBeClickable(getBy(ROLES_ROW_BY_TEXT, name)).click();
  }

  public void clickOnRoleNameColumnHeader() {
    waitForElementToBeClickable(getBy(ROLES_NAME_COLUMN_HEADER)).click();
  }

  public void editRoleName(String value) {
    editField(roleName, value);
  }

  public void editSearchField(String value) {
    editField(searchField, value);
    searchField.sendKeys(Keys.ENTER);
  }

  public int getNumberOfRolesRows() {
    return findElements(getBy(ROLES_ROWS)).size();
  }

  public int getNumberOfGroupRows() {
    return findElements(getBy(GROUPS_ROWS)).size();
  }

  public List<String> getListOfRolesNames() {
    return getTexts(getBy(ROLES_NAMES_CELLS));
  }
}