package pages;

import core.BasePage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import java.util.Arrays;

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

  private static final String ARROW_BY_SIBLING_LABEL =
      "//span[contains(@class,'ag-row-group')][span[contains(.,'%s')]]//span[contains(@class,'closed')]";
  private static final String ACTION_BY_NAME = "//static-column-tree-grid//*[text()='%s']";
  private static final String BUTTON_BY_NAME = "//button[contains(.,'%s')]";
  private static final String BUTTON_ON_DIALOG_BY_NAME = "//div[@class='modal-body']//button[contains(.,'%s')]";
  private static final String MODAL_TITLE_BY_NAME = "//*[@class='modal-title'][contains(.,'%s')]";
  private static final String ROLE_BY_NAME = "//static-column-grid//div[@class='ag-cell-wrapper']//span[contains(.,'%s')]";

  private static final By COMBOBOX_INPUT = By.xpath(
      "//combo-box//div[contains(@class,'selectize-input')]//input");

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

  public void openActionTree(String... actions) {
    Arrays.asList(actions)
        .forEach(action -> waitForElementToBeClickable(getBy(ARROW_BY_SIBLING_LABEL, action)).click());
  }

  public void clickOnAction(String action) {
    waitForElementToBeClickable(getBy(ACTION_BY_NAME, action)).click();
  }

  public void clickOnButton(String name) {
    waitForElementToBeClickable(getBy(BUTTON_BY_NAME, name)).click();
  }

  public void clickOnButtonOnDialog(String name) {
    waitForElementToBeClickable(getBy(BUTTON_ON_DIALOG_BY_NAME, name)).click();
  }

  public boolean isDialogOpened(String title) {
    return isPresent(getBy(MODAL_TITLE_BY_NAME, title));
  }

  public void selectRole(String value) {
    typeAndSelectValue(COMBOBOX_INPUT, value);
  }

  public void clickOnRole(String role) {
    waitForElementToBeClickable(getBy(ROLE_BY_NAME, role)).click();
  }

  public boolean isRoleOnTheList(String role) {
    return isPresent(getBy(ROLE_BY_NAME, role));
  }
}