package old.page;

import java.time.Duration;

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

import static org.junit.jupiter.api.Assertions.assertTrue;

public class LoginPage extends BaseComponentPage {
  private static final By ERROR_LOGIN = By.xpath("//div[@class='form-signin']//div[contains(@class,'alert-danger')]");
  private static final By TEXT_ERROR_DEPLOY_MESSAGE = By.xpath("//*[contains(., 'Приложение стартует')]");
  private static final By LOGIN_PAGE_HEADER = By.xpath("//*[contains(text(), 'Вход')]");

  @FindBy(name = "username")
  private WebElement emailInput;
  @FindBy(name = "password")
  private WebElement passwordInput;
  @FindBy(css = "button[class='btn btn-primary']")
  private WebElement enterButton;
  @FindBy(xpath = "//*[contains(text(), 'Забыли пароль?')]")
  private WebElement resetPasswordLink;
  @FindBy(xpath = "//*[contains(text(), 'Зарегистрироваться')]")
  private WebElement registrationLink;


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

  public void typeLoginPasswordAndEnter(String login, String password) {
    waitForVisibilityOfElementLocated(EMAIL_INPUT_BY);
    passwordInput.clear();
    passwordInput.sendKeys(password);
    emailInput.clear();
    emailInput.sendKeys(login);
    enterButton.click();
  }

  public InboxPage login(String login, String password) {
    typeLoginPasswordAndEnter(login, password);
    assertTrue(hasNoErrorOnLoginPage(TEXT_ERROR_DEPLOY_MESSAGE), "Failed to deploy backend");
    assertTrue(hasNoErrorOnLoginPage(ERROR_LOGIN), "Failed to login");
    waitProgressBarNotVisible();

    assertTrue(thereIsNoError());
    return PageFactory.initElements(driver, InboxPage.class);
  }

  private boolean hasNoErrorOnLoginPage(By locator) {
    try {
      waitForInvisibilityOfElementLocated(locator, Duration.ofSeconds(5));
    }
    catch (TimeoutException ignored) {
      logger.error(getErrorText(locator));
      return false;
    }
    return true;
  }

  public String getErrorTextFromLoginForm() {
    return getErrorText(ERROR_LOGIN);
  }

  public void goToResetPage() {
    waitForVisibilityOfElementLocated(LOGIN_PAGE_HEADER);
    resetPasswordLink.click();
  }

  public void goToRegistPage(){
    waitForPageLoad();
    registrationLink.click();
  }
}