/**
 * atk_feeds.cy.js
 *
 * Validate feeds entity.
 *
 */

/** ESLint directives */
/* eslint-disable import/first */

/// <reference types='Cypress' />

// Set up ATK.
import * as atkCommands from '../../support/atk_commands' // eslint-disable-line no-unused-vars
import * as atkUtilities from '../../support/atk_utilities'
import atkConfig from '../../../cypress.atk.config'

// Standard accounts that use user accounts created
// by QA Accounts. QA Accounts are created when the QA
// Accounts module is enabled.
import qaUserAccounts from '../../data/qaUsers.json'

describe('Feed Tests', () => {
  const ctx = {
    feedTypeName: undefined,
  }

  //
  // Create a new feed definition, import fixture, validate that data is in the database.
  //
  it('(ATK-PW-1180) Creates the feed type settings', { tags: ['@ATK-PW-1180', '@feeds', '@alters-db'] }, () => {
    const testId = 'ATK-CY-1180'
    const uniqueToken = atkUtilities.createRandomString(6)
    const feedTypeName = `${testId}: ${uniqueToken}`

    // Log in with the administrator account.
    // Assuming logInViaForm is adapted for cypress.
    cy.logInViaForm(qaUserAccounts.admin)
    cy.visit(atkConfig.feedTypeAddUrl)

    //
    // Add a Feed type
    //

    // Fill in the fields.
    cy.contains('Name').type(feedTypeName)
    cy.contains('Description').type('Import feeds')
    cy.contains('Explanation').type('ATK Feeds Test')

    // Set the Source from Fetcher.
    cy.get('label[for="edit-fetcher"]').click()

    // Choose Fetcher type.
    cy.get('select#edit-fetcher').select('Download from url')

    // Select parser settings.
    cy.get('label[for="edit-parser"]').click()
    cy.get('select#edit-parser').select('RSS/Atom')

    // Choose the data processor.
    cy.get('label[for="edit-processor"]').click()
    cy.get('select#edit-processor').select('Node')

    // Pick Content Type.
    cy.get('label[for="edit-processor-wrapper-advanced-values-type"]').click()
    cy.get('select#edit-processor-wrapper-advanced-values-type').select('Article')

    // Save the configured feed type.
    cy.contains('Save and add mappings').click()
    ctx.feedTypeName = feedTypeName

    // Create mapping for imports
    cy.get('#edit-add-target').first().select('Title (title)')
    cy.get('select[data-drupal-selector="edit-mappings-0-map-value-select"]').select('Title')

    // Save mapping structure
    cy.get('[data-drupal-selector="edit-actions-submit"]').click()
  })

  it('(ATK-PW-1181) Passes and imports items', { tags: ['@ATK-PW-1181', '@feeds', 'alters-db'] }, () => {
    // ctx.feedTypeName must exist to run this test.
    cy.wrap(ctx.feedTypeName).should('not.be.undefined', { message: 'Feed type must exist for this test' })

    // Login via admin account.
    cy.logInViaForm(qaUserAccounts.admin)

    //
    // Add a new feed into the existing feed type.
    //
    cy.visit(atkConfig.feedAddUrl)

    // Find the existing feed type,
    // check if it's the only feed (we just navigated to the form).
    cy.url().then((url) => {
      const regExpMatchArray = /feed\/add\/(\w+)/[Symbol.match](url)
      if (regExpMatchArray) {
        cy.log(`Adding feed for **${regExpMatchArray[1]}**`)
      } else {
        // Select the feed that you have created.
        cy.contains('a:visible', ctx.feedTypeName).click()
      }
    })
    cy.contains('Title').type('nytimes rss business')

    //
    // Insert path to Import file or the data file URL.
    // {baseURL} substitution to host:port.
    //
    const { host } = new URL(Cypress.config('baseUrl'))
    const xmlUrl = atkConfig.feedXmlUrl.replace('{baseURL}', host)
    cy.contains('Feed URL').type(xmlUrl)

    // Save and export the feed.
    cy.contains('Save and import').click()
    cy.contains('nytimes rss business has been created.')

    // Validate that content items are created.
    cy.visit('admin/content')
    cy.contains('tr', atkConfig.feedItem)
  })

  after(() => {
    //
    // Clean up.
    //
    cy.visit('admin/content/feed')
    cy.contains('tr', ctx.feedTypeName).then(($el) => {
      if ($el.length) {
        const deleteItemsUrl = $el.find('a:contains("Delete items")').attr('href')
        const deleteUrl = $el.find('[aria-label^="Delete nytimes"]').attr('href')
        cy.visit(deleteItemsUrl)
        cy.get('#edit-submit').click({ force: true })
        cy.get('h2[id^="status"]') // Wait to finish delete
        cy.visit(deleteUrl)
        cy.get('#edit-submit').click({ force: true })
      }
    })

    cy.visit('admin/structure/feeds')
    cy.contains('tr', ctx.feedTypeName).then(($el) => {
      if ($el.length) {
        const deleteUrl = $el.find('[aria-label^="Delete ATK"]').attr('href')
        cy.visit(deleteUrl)
        cy.get('#edit-submit').click({ force: true })
      }
    })
  })
})
