// ***********************************************************
// 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) => {
          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 }
              }
              // eslint-disable-next-line no-restricted-syntax
              for (const [conditionType, conditionValue] of Object.entries(condition)) {
                switch (conditionType) {
                  case 'eq':
                    expect(value, prerequisite.message).to.eq(conditionValue)
                    break
                  // ...
                  default:
                    throw new Error(`Condition ${conditionType} is not implemented`)
                }
              }
            }
          }
        })
      }
    }
  })
})
