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

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

// Set up Playwright.
import { expect, test } from '@playwright/test'

import * as atkCommands from '../support/atk_commands'
import * as atkUtilities from '../support/atk_utilities'

import playwrightConfig from '../../playwright.config'

const baseUrl = playwrightConfig.use.baseURL // eslint-disable-line no-unused-vars

// Import ATK Configuration.
import atkConfig from '../../playwright.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'

test.describe('Feeds.', () => {
  // Remember names for clean up.
  const ctx = {
    feedTypeName: null,
    adminPage: null,
  }

  test.beforeEach(async ({ browser }) => {
    ctx.adminPage = await atkCommands.getUserPage(browser, qaUserAccounts.admin)
  })

  //
  // Create a new feed definition, import fixture, validate that data is in the database.
  //
  test('(ATK-PW-1180) Feeds Test using Playwright. Tags : @ATK-PW-1180, @feeds, @alters-db', async () => {
    const { adminPage } = ctx
    //
    // Add a Feed type
    //
    await adminPage.goto(atkConfig.feedTypeAddUrl)

    // Make a unique feed name.
    ctx.feedTypeName = `Import with url ${atkUtilities.createRandomString(10)}`

    // Fill in the fields
    await adminPage.getByLabel('Name', { exact: true }).click()
    await adminPage.getByLabel('Name', { exact: true }).fill(ctx.feedTypeName)
    await adminPage.getByLabel('Description').click()
    await adminPage.getByLabel('Description').fill('Import feeds')
    await adminPage.getByLabel('Explanation or submission').click()
    await adminPage.getByLabel('Explanation or submission').fill('Atk feeds test')

    // Save the configured feed type
    await adminPage.getByRole('button', { name: 'Save and add mappings' }).click()
    await adminPage.waitForEvent('domcontentloaded')

    //
    // Create mapping for imports
    //
    await adminPage.getByLabel('Add a target').selectOption('title')
    await adminPage.locator('[data-drupal-selector="edit-mappings-0-map-value-select"]').selectOption('title')
    await adminPage.getByLabel('Add a target').selectOption('body')
    await adminPage.locator('[data-drupal-selector="edit-mappings-1-map-value-select"]').selectOption('feed_description')
    await adminPage.locator('[data-drupal-selector="edit-mappings-1-map-summary-select"]').selectOption('feed_title')
    await adminPage.getByLabel('Add a target').selectOption('feeds_item')
    await adminPage.locator('[data-drupal-selector="edit-mappings-2-map-url-select"]').selectOption('url')
    await adminPage.locator('[data-drupal-selector="edit-mappings-2-map-guid-select"]').selectOption('guid')
    await adminPage.getByRole('button', { name: 'Save' }).click()

    //
    // Add a new feed into the existing feed type.
    //
    await adminPage.goto(atkConfig.feedAddUrl)

    // Find the existing feed type.
    // Select the feed that you have created.
    const regExpMatchArray = adminPage.url().match(/feed\/add\/(\w+)/)
    if (regExpMatchArray) {
      // Creating feed for the only existing feed type.
    } else {
      await adminPage.getByRole('link', { name: ctx.feedTypeName }).click()
    }
    await adminPage.getByLabel('Title').click()
    await adminPage.getByLabel('Title').fill('nytimes rss business')

    //
    // Insert path to Import file or the data file URL.
    //
    await adminPage.getByLabel('Feed URL').click()
    const { host } = new URL(baseUrl)
    const xmlUrl = atkConfig.feedXmlUrl.replace('{baseURL}', host)
    await adminPage.getByLabel('Feed URL').fill(xmlUrl)

    // Save and export the feed.
    await adminPage.getByRole('button', { name: 'Save and import' }).click()
    await adminPage.getByText('nytimes rss business has been created.', { exact: true }).waitFor()

    // Validate that at least one article is created.
    await adminPage.goto('admin/content')
    await expect(adminPage.locator('tr', { hasText: atkConfig.feedItem })).toBeVisible()
  })

  test.afterEach(async () => {
    //
    // Clean up the created entities.
    //
    const { adminPage, feedTypeName } = ctx

    // Delete feed items and delete a feed.
    await adminPage.goto('admin/content/feed')
    const rowLocator = adminPage.locator('tr', { hasText: feedTypeName })

    // Skip if the feed doesn't exist.
    if (await rowLocator.count()) {
      await rowLocator.locator('.dropbutton__toggle').click()
      await rowLocator.getByText('Delete items').click()
      await adminPage.getByRole('button', { name: 'Delete items' }).click()
      await rowLocator.waitFor() // Should we navigate back to the feed row.

      await rowLocator.locator('.dropbutton__toggle').click()
      await rowLocator.getByText('Delete', { exact: true }).click()
      await adminPage.getByRole('button', { name: 'Delete' }).click()
    }

    // Delete feed type.
    await adminPage.goto('admin/structure/feeds')
    // Skip if the feed type doesn't exist.
    if (await rowLocator.count()) {
      await rowLocator.locator('.dropbutton__toggle').click()
      await rowLocator.getByText('Delete').click()
      await adminPage.getByRole('button', { name: 'Delete' }).click()
    }
  })
})
