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

context('csv file upload restriction (free tier): ', function () {
  this.beforeEach(() => {
    cy.visit(hostUrl + appLocation)

    cy.get('body').then(($body) => {
      const usernameInput = $body.find('input.username')[0]

      if (usernameInput && !Cypress.dom.isHidden(usernameInput)) {
        cy.get('input.username').type(username)
        cy.get('input.password').type(password)
        cy.get('.login-group button').click()
      }
    })

    cy.get('.app-loading', { timeout: longerCommandTimeout }).should(
      'not.exist'
    )

    // Skip licensing page if presented - continue with free tier
    cy.url().then((url) => {
      if (url.includes('licensing')) {
        cy.get('button').contains('Continue with free tier').click()
      }
    })

    visitPage('home')
  })

  it('1 | File upload is restricted on free tier', () => {
    openTableFromTree(libraryToOpenIncludes, 'mpe_x_test')

    // Click upload button - should show feature locked modal
    cy.get('.buttonBar button:last-child').should('exist').click()

    cy.get('.modal-title').should('contain', 'Locked Feature (File Upload)')
  })
})

const openTableFromTree = (libNameIncludes: string, tablename: string) => {
  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 targetLib

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

        cy.get(targetLib).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()
                break
              }
            }
          })
        })
      })
    })
}

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

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