import BasePage from "./BasePage";

class LoginPage extends BasePage {
  // Selectors
  get pageTitle() {
    return $("h1");
  }

  get serverUrlInput() {
    return $("#server-url");
  }

  get connectButton() {
    return $('button[type="submit"]');
  }

  get usernameInput() {
    return $("#username");
  }

  get passwordInput() {
    return $("#password");
  }

  get signInButton() {
    return $('button[type="submit"]');
  }

  get errorMessage() {
    return $(".bg-red-900\\/50");
  }

  get backButton() {
    return $("button*=Back");
  }

  get serverNameDisplay() {
    return $('p.text-\\[var\\(--color-jellyfin\\)\\]');
  }

  // Actions
  async waitForLoginPage(timeout: number = 10000) {
    await this.serverUrlInput.waitForDisplayed({ timeout });
  }

  async enterServerUrl(url: string) {
    await this.serverUrlInput.setValue(url);
  }

  async clickConnect() {
    await this.connectButton.click();
  }

  async connectToServer(url: string) {
    await this.enterServerUrl(url);
    await this.clickConnect();

    // Wait for transition to login form
    await this.usernameInput.waitForDisplayed({ timeout: 10000 });
  }

  async enterUsername(username: string) {
    await this.usernameInput.setValue(username);
  }

  async enterPassword(password: string) {
    await this.passwordInput.setValue(password);
  }

  async clickSignIn() {
    await this.signInButton.click();
  }

  async login(username: string, password: string) {
    await this.enterUsername(username);
    await this.enterPassword(password);
    await this.clickSignIn();
  }

  async fullLoginFlow(serverUrl: string, username: string, password: string) {
    await this.waitForLoginPage();
    await this.connectToServer(serverUrl);
    await this.login(username, password);
  }

  async isOnServerStep(): Promise<boolean> {
    try {
      return await this.serverUrlInput.isDisplayed();
    } catch {
      return false;
    }
  }

  async isOnLoginStep(): Promise<boolean> {
    try {
      return await this.usernameInput.isDisplayed();
    } catch {
      return false;
    }
  }

  async getErrorMessage(): Promise<string> {
    await this.errorMessage.waitForDisplayed({ timeout: 5000 });
    return await this.errorMessage.getText();
  }

  async hasError(): Promise<boolean> {
    try {
      return await this.errorMessage.isDisplayed();
    } catch {
      return false;
    }
  }
}

export default new LoginPage();
