package old.page;

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

import java.util.List;
import java.time.Duration;

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

  private static final By CELL_WITH_NAME = By.xpath(
      "//*[@object-name='Древовидная таблица']//div[@col-id='name'][not(contains(@class,'ag-header'))]//span[@class='ag-group-value']");
  private static final By GRID_BODY =
      By.xpath("//div[@class='ag-center-cols-container'][//div[@role='row'][not(contains(@class,'ag-header'))]]");
  private static final String PLUS_IN_CELL_WITH_NAME =
      "//div[@col-id='name'][//span[contains(text(), '%s')]]//span[@ref='eContracted']";
  private static final String CHECKBOX_BY_NAME =
      "//div[@col-id='name'][.//span[contains(text(), '%s')]]//div[contains(@class,'ag-selection-checkbox')]";

  //Organization Editing Page
  @FindBy(xpath = "//*[@object-name='Группа фильтров']//input")
  private WebElement searchField;
  @FindBy(xpath = "//div[label[span[contains(.,'Наименование')]]]//input")
  public WebElement nameField;
  @FindBy(xpath = "//div[label[span[contains(.,'Код')]]]//input")
  private WebElement codeField;

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

  public void fillOrgNameAndCode(String name) {
    typeText(nameField, name);
    typeText(codeField, name);
  }

  public void chooseParentOrg(String parentOrgName) {
    typeTextAndSelectOption("Выпадающий список (с возможностью сохранения)", parentOrgName, parentOrgName);
  }

  public void searchOrg(String name) {
    typeTextOnAdminFilter(searchField, name);
    waitForInvisibilityGridDownloader();
  }

  public List<WebElement> getListOfOrganizationsFromTable() {
    return driver.findElements(CELL_WITH_NAME);
  }

  public void clickOnPlusSign(String orgName) {
    waitForVisibilityOfElementLocated(By.xpath(String.format(PLUS_IN_CELL_WITH_NAME, orgName))).click();
    waitProgressBarNotVisible();
  }

  public void searchAndClickOnOrg(String name) {
    if (driver.findElements(By.xpath(String.format(CHECKBOX_BY_NAME, name))).isEmpty()) {
      searchOrg(name);
    }
    waitForVisibilityOfElementLocated(By.xpath(String.format(CHECKBOX_BY_NAME, name))).click();
    waitForPageLoad();
  }

  public void deleteOrg() {
    clickDeleteButton();
    confirmAction();
  }

  public void cancelEditingOrg() {
    clickCancelButton();
    confirmAction();
  }

  private void confirmAction() {
    clickConfirmButton();
    waitProgressBarNotVisible();
    waitForPageLoad();
  }

  public void waitGridEmpty() {
    waitForInvisibilityOfElementLocated(GRID_BODY, Duration.ofSeconds(60));
  }

  public void waitOrgEditingPageLoading() {
    waitForPageLoad();
    waitForVisibilityOf(nameField);
  }
}
