import test from 'ava'
import { resolve } from 'path'
import { Nuxt, Builder, Utils } from '..'
import { uniq } from 'lodash'

const port = 4008
let nuxt = null

// Utils
const range = n => [...Array(n).keys()]
const FOOBAR_REGEX = /<foobar>([\s\S]*)<\/foobar>/
const match = (regex, text) => (regex.exec(text) || [])[1]

// Init nuxt.js and create server listening on localhost:4000
test.before('Init Nuxt.js', async t => {
  const options = {
    rootDir: resolve(__dirname, 'fixtures/ssr'),
    dev: false,
    render: {
      resourceHints: false
    },
    build: {
      extractCSS: true
    }
  }
  nuxt = new Nuxt(options)
  await new Builder(nuxt).build()
  await nuxt.listen(port, 'localhost')
})

// == Uniq Test ==
// The idea behind is pages using a shared nextId() which retuns an increamenting id
// So all responses should strictly be different and length of unique responses should equal to responses
// We strictly compare <foorbar>{id}</foorbar> section
// Because other response parts such as window.__NUXT may be different resulting false positive passes.
const uniqueTest = async (t, url) => {
  let results = []

  await Utils.parallel(range(20), async () => {
    let { html } = await nuxt.renderRoute(url)
    let foobar = match(FOOBAR_REGEX, html)
    results.push(parseInt(foobar))
  })

  let isUnique = uniq(results).length === results.length

  if (!isUnique) {
    /* eslint-disable no-console */
    console.log(url + '\n' + results.join(', ') + '\n')
  }

  t.true(isUnique)

  return results
}

test('unique responses with data()', async t => {
  await uniqueTest(t, '/data')
})

test('unique responses with component', async t => {
  await uniqueTest(t, '/component')
})

test('unique responses with async components', async t => {
  await uniqueTest(t, '/asyncComponent')
})

test('unique responses with asyncData()', async t => {
  await uniqueTest(t, '/asyncData')
})

test('unique responses with store initial state', async t => {
  await uniqueTest(t, '/store')
})

test('unique responses with nuxtServerInit', async t => {
  await uniqueTest(t, '/store?onServerInit=1')
})

test('unique responses with fetch', async t => {
  await uniqueTest(t, '/fetch')
})

// Close server and ask nuxt to stop listening to file changes
test.after('Closing server and nuxt.js', t => {
  nuxt.close()
})

@@ -118,16 +118,56 @@
 'lodash'
+%0Aimport rp from 'request-promise-native'
 %0A%0Aconst 
@@ -355,16 +355,75 @@
 %5B%5D)%5B1%5D%0A%0A
+const url = (route) =%3E 'http://localhost:' + port + route%0A%0A
 // Init 
@@ -881,16 +881,17 @@
 ich retu
+r
 ns an in
@@ -893,17 +893,16 @@
 an incre
-a
 menting 
@@ -2248,32 +2248,32 @@
 ', async t =%3E %7B%0A
-
   await uniqueTe
@@ -2292,16 +2292,860 @@
 h')%0A%7D)%0A%0A
+// == Stress Test ==%0A// The idea of this test is to ensure there is no memory or data leak during SSR requests%0A// Or pending promises/sockets and function calls.%0A// Making 16K requests by default%0A// Related issue: https://github.com/nuxt/nuxt.js/issues/1354%0Aconst stressTest = async (t, _url, concurrency = 64, steps = 256) =%3E %7B%0A  let statusCodes = %7B %7D%0A%0A  await Utils.sequence(range(steps), async () =%3E %7B%0A    await Utils.parallel(range(concurrency), async () =%3E %7B%0A      let response = await rp(url(_url), %7B resolveWithFullResponse: true %7D)%0A      // Status Code%0A      let code = response.statusCode%0A      if (!statusCodes%5Bcode%5D) %7B%0A        statusCodes%5Bcode%5D = 0%0A      %7D%0A      statusCodes%5Bcode%5D++%0A    %7D)%0A  %7D)%0A%0A  t.is(statusCodes%5B200%5D, concurrency * steps)%0A%7D%0A%0Atest('stress test with asyncData', async t =%3E %7B%0A  await stressTest(t, '/asyncData')%0A%7D)%0A%0A
 // Close

add stress test for asyncData