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

// SAS Visual Analytics data-driven content embed mode (`?embed=va`):
//  - chrome is hidden (same as embed=true),
//  - the editor opens in edit mode immediately (not read-only),
//  - the only action button is a single Submit below the grid (stubbed in v1),
//  - the top button bar and Add Record are hidden.
//
// The detailed PK+label data-merge logic is covered by the VaMessagingService
// unit spec; here we only assert the deterministic UI layout and that pushing a
// VA postMessage does not break the page.
context('embed=va (VA data-driven content) tests: ', function () {
  this.beforeAll(() => {
    cy.visit(`${hostUrl}/SASLogon/logout`)
    cy.loginAndUpdateValidKey()
  })

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

  it('1 | opens the editor in VA mode: chrome hidden, editable, single bottom Submit', () => {
    openEditorInVaMode('mpe_x_test', () => {
      // Chrome hidden (same as embed=true)
      cy.get('header.app-header').should('not.exist')

      // Grid present and in edit mode (read-only Filter/Edit/Upload bar absent)
      cy.get('#hotTable', { timeout: longerCommandTimeout }).should('exist')
      cy.get('.btnCtrl button').contains('Edit').should('not.exist')
      cy.get('.btnCtrl button').contains('Filter').should('not.exist')

      // Top edit-mode buttons hidden in VA mode
      cy.get('.btnCtrl button.btn-outline-danger').should('not.exist') // Cancel
      cy.get('.btnCtrl').contains('Add Row').should('not.exist')

      // Bottom Add Record hidden
      cy.contains('button', 'Add Record').should('not.exist')

      // Exactly one Submit button, below the grid, disabled in v1
      cy.get('button').filter(':contains("Submit")').should('have.length', 1)
      cy.get('button').contains('Submit').should('be.disabled')
    })
  })

  it('2 | accepts a VA postMessage and stays in VA mode', () => {
    // A VA message drives column visibility + filtering; an empty/unmatched
    // message reloads the editor (unfiltered) while preserving ?embed=va.
    openEditorInVaMode('mpe_x_test', () => {
      cy.window().then((win) => {
        win.postMessage(
          {
            version: '1',
            resultName: 'dd1',
            rowCount: 0,
            availableRowCount: 0,
            data: [],
            columns: [],
            parameters: []
          },
          '*'
        )
      })

      // Editor still loads in VA mode after the message (chrome hidden, grid up)
      cy.get('#hotTable', { timeout: longerCommandTimeout }).should('exist')
      cy.get('header.app-header').should('not.exist')
      cy.get('button').contains('Submit').should('exist')
    })
  })
})

// Opens a table from the tree (which routes to #/editor/LIB.TABLE), then
// re-visits the same route with ?embed=va so the app parses VA embed mode.
const openEditorInVaMode = (tablename: string, callback?: any) => {
  openTableFromTree(libraryToOpenIncludes, tablename)

  cy.get('#hotTable', { timeout: longerCommandTimeout })
    .should('exist')
    .then(() => {
      cy.url().then((url) => {
        const separator = url.includes('?') ? '&' : '?'
        cy.visit(`${url}${separator}embed=va`)
        cy.get('.app-loading', { timeout: longerCommandTimeout }).should(
          'not.exist'
        )
        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}`)
}
