const { assign, camelCase, find, get, set } = require('lodash')
const { client } = require('nightwatch-cucumber')
const { When } = require('cucumber')

const fixtures = require('../../fixtures')

When(/^I (?:navigate|go|open|visit).*? `(.+)` page$/, async function (pageName) {
  try {
    const page = get(client.page, pageName)()
    await page.navigate()
  } catch (error) {
    throw new Error(`The page object '${pageName}' does not exist`)
  }
})

When(/^I (?:navigate|go|open|visit).*? `(.+)` page using `(.+)` `(.+)` fixture$/, async function (pageName, entity, fixtureName) {
  try {
    const page = get(client.page, pageName)()

    const fixture = find(fixtures[entity], { name: fixtureName })

    // TODO: Need to find a way to remove needing to store the item in state
    const entityTypeFieldName = camelCase(entity)
    set(this.state, entityTypeFieldName, assign({}, get(this.state, entityTypeFieldName), fixture))

    await page.navigate(page.url(fixtureName))
  } catch (error) {
    throw new Error(`The page object '${pageName}' does not exist`)
  }
})

When('I click the {string} link', async function (linkText) {
  await client
    .useXpath()
    .click(`//a[text()='${linkText}']`)
    .useCss()
})

When(/^I click `(.+)` on the `(.+)` page$/, async function (elementName, pageName) {
  try {
    const page = get(client.page, pageName)()
    await page.click(`@${elementName}`)
  } catch (error) {
    throw new Error(`The page object '${pageName}' does not exist`)
  }
})

When(/^I select a value for `(.+)` on the `(.+)` page$/, async function (elementName, pageName) {
  try {
    const page = get(client.page, pageName)()
    await page
      .getListOption(`@${elementName}`, (item) => {
        page.setValue(`@${elementName}`, item)
        set(this.state, `${pageName}[${elementName}]`, item)
      })
  } catch (error) {
    throw new Error(`The page object '${pageName}' does not exist`)
  }
})

@@ -119,16 +119,22 @@
 t %7B When
+, Then
  %7D = req
@@ -1914,28 +1914,354 @@
 e%7D' does not exist%60)%0A  %7D%0A%7D)%0A
+%0AThen(/%5EI am on the %60(.+)%60 page$/, async function (pageName) %7B%0A  try %7B%0A    const page = get(client.page, pageName)()%0A%0A    if (page.props.urlMatch) %7B%0A      await client.assert.urlMatch(page.props.urlMatch)%0A    %7D else %7B%0A      await client.assert.urlContains(page.url)%0A    %7D%0A  %7D catch (error) %7B%0A    throw new Error(error)%0A  %7D%0A%7D)%0A

Add step definition to check current page