// Marks this file as an ES module (rather than a global script) so its
// top-level consts don't collide, under the TS type-checker, with the same
// names declared in other spec files — see viewer-labels.cy.ts for the same
// pattern.
export {}

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}`)

// Regression coverage for issue #253's vertical-array COLTYPE fix — see
// getdata.sas now sends one COLTYPE JSON-object string per cols[] row (via
// a LEFT JOIN keyed off the real dataset's columns), instead of one
// comma-joined sasparams.COLTYPE string covering every column. Two things
// are specifically at risk from that change and aren't covered elsewhere:
//   1. `_____DELETE__THIS__RECORD_____` (the delete checkbox column) is a
//      client-side-only concept — %mp_getcols never has a row for it, so
//      it can no longer travel via cols[].COLTYPE at all. Its Yes/No
//      dropdown rule is now hardcoded client-side (deleteRecordColumnRule.ts)
//      — test 1 proves that hardcode actually renders end to end.
//   2. Ordinary columns (e.g. SOME_DROPDOWN) still get their rule via the
//      new per-row cols[].COLTYPE path — test 2 proves the migration didn't
//      silently drop real columns' rules either.
// Column positions below come from COLHEADERS in
// sas/mocks/sasjs/services/editors/getdata.js:
// "_____DELETE__THIS__RECORD_____,PRIMARY_KEY_FIELD,SOME_CHAR,SOME_DROPDOWN,..."
// — childNodes[0] on a body <tr> is the row-header <th>, so childNodes[N+1]
// is the Nth (0-indexed) column in that list.
context('coltype vertical-array regression tests: ', function () {
  this.beforeAll(() => {
    cy.visit(`${hostUrl}/SASLogon/logout`)
    cy.loginAndUpdateValidKey(true)
  })

  this.beforeEach(() => {
    cy.visit(hostUrl + appLocation)
    visitPage('home')
  })

  it('1 | delete-record column renders its hardcoded Yes/No dropdown', () => {
    openTableFromTree(libraryToOpenIncludes, 'mpe_x_test')
    clickOnEdit()

    cy.get('.ht_master tbody tr', { timeout: longerCommandTimeout }).then(
      (rows: any) => {
        // childNodes[1] = _____DELETE__THIS__RECORD_____ (1st column)
        cy.get(rows[1].childNodes[1])
          .click({ force: true })
          .then(($td) => {
            cy.get('.htAutocompleteArrow', { withinSubject: $td })
              .should('exist')
              .click({ force: true })

            cy.get('.autocompleteEditor .htCore tbody td').should(
              ($choices) => {
                const texts = [...$choices].map((el) => el.innerText.trim())
                expect(texts).to.deep.equal(['No', 'Yes'])
              }
            )
          })
      }
    )
  })

  it('2 | an ordinary dropdown column (SOME_DROPDOWN) still gets its rule from cols[].COLTYPE', () => {
    openTableFromTree(libraryToOpenIncludes, 'mpe_x_test')
    clickOnEdit()

    cy.get('.ht_master tbody tr', { timeout: longerCommandTimeout }).then(
      (rows: any) => {
        // childNodes[4] = SOME_DROPDOWN (4th column, 0-indexed as 3). This
        // only holds if DcValidator emits rules in VARNUM order — see the
        // "orders rules by VARNUM" regression test in dc-validator.spec.ts.
        cy.get(rows[1].childNodes[4])
          .click({ force: true })
          .then(($td) => {
            cy.get('.htAutocompleteArrow', { withinSubject: $td }).should(
              'exist'
            )
          })
      }
    )
  })
})

const clickOnEdit = (callback?: any) => {
  cy.get('.btnCtrl button.btn-primary', { timeout: longerCommandTimeout })
    .click()
    .then(() => {
      if (callback) callback()
    })
}

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 viyaLib

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

        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()
                break
              }
            }
          })
        })
      })
    })
}

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