const username = Cypress.env('username')
const password = Cypress.env('password')
const hostUrl = Cypress.env('hosturl')
const appLocation = Cypress.env('appLocation')
const longerCommandTimeout = Cypress.env('longerCommandTimeout')
const serverType = Cypress.env('serverType')
const libraryToOpenIncludes = Cypress.env(`libraryToOpenIncludes_${serverType}`)
const fixturePath = 'excels_general/'

context('metanav tests: ', function () {
  this.beforeAll(() => {
    cy.visit(`${hostUrl}/SASLogon/logout`)
    cy.loginAndUpdateValidKey()
  })

  this.beforeEach(() => {
    cy.visit(hostUrl + appLocation)
    cy.get('input.username').type(username)
    cy.get('input.password').type(password)
    cy.get('.login-group button').click()

    visitPage('view/metadata')
  })

  it('1 | Opens metadata object', (done) => {
    openFirstMetadataFromTree(() => {
      // BLOCKER
      // For unkown reasons, .clr-accordion-header-button always null although it is present on the page.
      cy.get('.clr-accordion-header-button').then((panelNodes: any) => {
        panelNodes[0].querySelector('button').click()
      })
    })
  })

  this.afterEach(() => {
    cy.visit(`${hostUrl}/SASLogon/logout`)
  })
})

const openFirstMetadataFromTree = (callback?: any) => {
  cy.get('.app-loading', { timeout: longerCommandTimeout })
    .should('not.exist')
    .then(() => {
      cy.get('.nav-tree clr-tree > clr-tree-node', {
        timeout: longerCommandTimeout
      }).then((treeNodes: any) => {
        let firstMetaNode

        firstMetaNode = treeNodes[1]

        cy.get(firstMetaNode).within(() => {
          cy.get('.clr-treenode-content').click()
          callback()
        })
      })
    })
}

const visitPage = (url: string) => {
  cy.visit(`${hostUrl}${appLocation}/#/${url}`)
}
