/*
 * Copyright (C) 2019 Robert Bosch GmbH Copyright (C) 2019 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

export class MacmaAppPo {
  constructor(private baseHref: string = '/') {}

  navigateToMacma() {
    cy.visit(this.baseHref + '?auth-provider=macma');
  }

  navigateToMacmaTenant(tenant: string) {
    cy.visit(this.baseHref + '?auth-provider=macma&tenant=' + tenant);
  }

  getTitle() {
    return cy.get('.sidenav-header h1');
  }

  getSidebarLoginLogoutButton() {
    return cy.get('#sidenav-login-logout');
  }

  getSidebarLogoutButton() {
    return cy.get('#sidenav-login-logout .Bosch-Ic-user');
  }

  getSidebarLoginButton() {
    return cy.get('#sidenav-login-logout .Bosch-Ic-log-in');
  }

  getBoschLogo() {
    return cy.get('.header-logo img');
  }

  getSidebar() {
    return cy.get('bci-sidebar');
  }

  getSidebarItemByText(menuItemText: string) {
    return cy.contains('p.mat-line', menuItemText);
  }

  getOverlayBackdrop() {
    return cy.get('.cdk-overlay-backdrop');
  }

  getLogoutOverlay() {
    return cy.get('bci-logout');
  }

  getLogoutOverlayCloseButton() {
    return cy.get('bci-logout button.close-button');
  }

  getLogoutOverlayLogoutButton() {
    return cy.contains('bci-logout button', 'Logout');
  }

  isApplicationLoaded() {
    return this.getTitle().should('exist').should('be.visible');
  }

  makeLoggedOut() {
    this.isApplicationLoaded();
    this.getSidebarLoginLogoutButton().should('be.visible');
    this.getSidebarLoginButton().should('exist').should('be.visible');

    this.logout();

    this.isLoggedOut();
  }

  logout() {
    console.log('Logging out...');
    this.getSidebarLoginLogoutButton().click();
    this.getSidebarLoginLogoutButton().should('be.visible');
    this.isLoggedOut();
  }

  login(username: string, password: string) {
    this.getSidebarLoginLogoutButton().click();

    cy.get('iframe').then(($iframe) => {
      const body = $iframe.contents().find('body');

      cy.wrap(body).find('#username').type(username);
      cy.wrap(body).find('#password').type(password);
      cy.get('[name="login"]').click();
    });
  }

  isLoggedIn() {
    return this.getSidebarLogoutButton().should('exist').should('be.visible');
  }

  isLoggedOut() {
    return this.getSidebarLoginButton().should('exist').should('be.visible');
  }

  getMacmaTestParams() {
    return {
      adminRealm: '7311ea8c-5d48-43fe-acf9-980eedf24b6c',
      adminUsername: 'e2e-web-core-auth',
      adminPassword: 'e2e-web-core-auth-pwd',
      testRealm: 'test-tenant',
      testAccessManagerUsername: 'e2e-web-core-auth',
      testAccessManagerPassword: 'e2e-web-core-auth-pwd',
    };
  }
}
