package pages;

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

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

  private static final By HEADER = By.xpath("//h2[contains(.,'Регистрация')]");
  private static final By PASSWORD_AS_TEXT = By.xpath("//input[@name='password'][@type='text']");
  private static final By PASSWORD_AS_SYMBOLS = By.xpath(
      "//input[@name='password'][@type='password']");
  private static final By REGISTRATION_BUTTON = By.xpath(
      "//div[@class='register-btn-box']//button");
  private static final By REGISTRATION_ERROR = By.xpath(
      "//div[@class='form-register']//div[contains(@class,'alert-danger')]");

  private static final String COUNTRY_BY_NAME = "//span[@class='country-name'][contains(.,'%s')]";

  @FindBy(xpath = "//a[contains(text(), 'Войти')]")
  private WebElement loginLink;
  @FindBy(xpath = "//span[@class='arrow-down']")
  private WebElement selectCountryArrowButton;
  @FindBy(xpath = "//div[@class='input-group-append'][.//i[contains(@class,'eye')]]")
  private WebElement passwordEyeButton;
  @FindBy(xpath = "//div//input[@name='username']")
  private WebElement usernameInput;
  @FindBy(xpath = "//div//input[@name='email']")
  private WebElement emailInput;
  @FindBy(xpath = "//div[contains(label,'Номер телефона')]//input")
  private WebElement phoneInput;
  @FindBy(xpath = "//div//input[@name='password']")
  private WebElement passwordInput;

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

  public boolean isHeaderVisible() {
    return isPresent(HEADER);
  }

  public void loginLinkClick() {
    loginLink.click();
  }

  public String getMaskForPhone() {
    return phoneInput.getAttribute("value");
  }

  public void selectCountry(String countryName) {
    selectCountryArrowButton.click();
    waitForVisibilityOfElementLocated(getBy(COUNTRY_BY_NAME, countryName)).click();
  }

  public void passwordEyeButtonClick() {
    passwordEyeButton.click();
  }

  public boolean isPasswordDisplayedAsText() {
    return isPresent(PASSWORD_AS_TEXT);
  }

  public boolean isPasswordDisplayedAsSymbols() {
    return isPresent(PASSWORD_AS_SYMBOLS);
  }

  public void editUsername(String value) {
    editField(usernameInput, value);
  }

  public void editEmail(String value) {
    editField(emailInput, value);
  }

  public void editPhone(String value) {
    editField(phoneInput, value);
  }

  public void editPassword(String value) {
    editField(passwordInput, value);
  }

  public void registerButtonClick() {
    waitForElementToBeClickable(REGISTRATION_BUTTON).click();
  }

  public String getRegistrationErrorText() {
    return waitForVisibilityOfElementLocated(REGISTRATION_ERROR).getText();
  }
}