// ***********************************************************
// This example support/e2e.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
import './atk_commands'
import { getProperty, readYAML } from './atk_utilities'

// Do environment check before all tests.
before(() => {
  readYAML('preflightTests.yml').then((prerequisites) => {
    // eslint-disable-next-line no-restricted-syntax
    for (const prerequisite of prerequisites) {
      if ('command' in prerequisite) {
        cy.execDrush(prerequisite.command).then((output) => {
          // Function to actually test the condition,
          // will lead to test failure for the obligatory conditions,
          // and warning if the condition has tag "warning".
          function doTest(condition, value) {
            // eslint-disable-next-line no-restricted-syntax
            if (condition.eq) {
              const message = condition.warning ?? prerequisite.message
              expect(value, message).to.eq(condition.eq)
            }
            // Implement other conditions if needed...
          }

          if (prerequisite.json) {
            const outputJson = JSON.parse(output)
            // Each property of prerequisite.json is a condition.
            // eslint-disable-next-line no-restricted-syntax,prefer-const
            for (let [key, condition] of Object.entries(prerequisite.json)) {
              const value = getProperty(outputJson, key)
              if (typeof condition !== 'object') {
                condition = { eq: condition }
              }
              if (condition.warning) {
                try {
                  doTest(condition, value)
                } catch (e) {
                  // Assertion will be in the log, but the test will continue.
                }
              } else {
                doTest(condition, value)
              }
            }
          }
        })
      }
    }
  })
})
