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/'

context('liveness tests: ', function () {
  this.beforeAll(() => {
    if (serverType !== 'SASJS') {
      cy.visit(`${hostUrl}/SASLogon/logout`)
    }
    cy.loginAndUpdateValidKey(true)
  })

  this.beforeEach(() => {
    cy.visit(hostUrl + appLocation)

    visitPage('home')
  })

  it('1 | Login and submit test', (done) => {
    cy.get('.nav-tree clr-tree > clr-tree-node', {
      timeout: longerCommandTimeout
    }).then((treeNodes: any) => {
      libraryExistsInTree('viya', treeNodes)
        ? openTableFromTree(libraryToOpenIncludes, 'mpe_x_test')
        : openTableFromTree('dc', 'mpe_x_test')

      attachExcelFile('regular_excel.xlsx', () => {
        submitExcel()
        rejectExcel(done)
      })
    })
  })

  /**
   * Thist part will be needed if we add more tests in future
   */
  // this.afterEach(() => {
  //     cy.visit('https://sas.4gl.io/SASLogon/logout');
  // })
})

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

const libraryExistsInTree = (libName: string, nodes: any) => {
  for (let node of nodes) {
    if (node.innerText.toLowerCase().includes(libName.toLowerCase()))
      return true
  }

  return false
}

const openTableFromTree = (
  libNameIncludes: string,
  tablename: string,
  finish: 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 viyaLib

        for (let node of treeNodes) {
          if (node.innerText.toLowerCase().includes(libNameIncludes)) {
            viyaLib = node
            break
          }
        }

        if (!viyaLib && finish) finish(false)

        cy.get(viyaLib).within(() => {
          cy.get('.clr-tree-node-content-container > button').click()

          cy.get('.clr-treenode-link').then((innerNodes: any) => {
            for (let innerNode of innerNodes) {
              if (innerNode.innerText.toLowerCase().includes(tablename)) {
                innerNode.click()
                if (finish) finish(true)
                break
              }
            }
          })
        })
      })
    })
}

const attachExcelFile = (excelFilename: string, callback?: any) => {
  cy.get('.buttonBar button:last-child')
    .should('exist')
    .click()
    .then(() => {
      cy.get('input[type="file"]#file-upload').attachFile(
        `/${fixturePath}/${excelFilename}`
      )
      cy.get('.modal-footer .btn.btn-primary').then((modalBtn) => {
        modalBtn.click()
        if (callback) callback()
      })
    })
}

const submitExcel = (callback?: any) => {
  cy.get('.buttonBar button.preview-submit', { timeout: longerCommandTimeout })
    .click()
    .then(() => {
      if (callback) callback()
    })
}

const rejectExcel = (callback?: any) => {
  cy.get('button', { timeout: longerCommandTimeout })
    .should('contain', 'Approve')
    .then((allButtons: any) => {
      for (let approvalButton of allButtons) {
        if (approvalButton.innerText.toLowerCase().includes('approve')) {
          approvalButton.click()
          break
        }
      }

      cy.get('button.btn-danger')
        .should('exist')
        .should('not.be.disabled')
        .click()
        .then(() => {
          cy.get('.modal-footer button.btn-success-outline')
            .click()
            .then(() => {
              cy.get('app-history')
                .should('exist')
                .then(() => {
                  if (callback) callback()
                })
            })
        })
    })
}
