import {expect} from 'chai'
import {spawn} from 'child_process'
import exec from '../../util/exec'
import launchAndWait from '../../util/launchAndWait'
import path from 'path'

async function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

function sharedTests() {
  it('serves page with correct title', async function () {
    expect(await browser.getTitle()).to.equal('Crater')
  })
  it('serves page with correct header', async function () {
    expect(await browser.getText('h1')).to.equal('Welcome to Crater!')
  })
  it('serves up client css', async function () {
    const color = await browser.getCssProperty('h1', 'color')
    expect(color.parsed.hex).to.equal('#333333')
  })
  it('updates the counter', async function() {
    const getCounter = async () => {
      const text = await browser.getText('h3')
      console.log(text)
      const match = /(\d+)/.exec(text)
      return match && parseInt(match[1])
    }

    const initCounter = await getCounter()
    await delay(2000)
    expect(await getCounter()).to.be.above(initCounter)
  })
}

describe('dev mode', function () {
  let server

  before(async function () {
    this.timeout(30000)
    server = await launchAndWait('npm start', /webpack built [a-z0-9]+ in \d+ms/i)
    await browser.url('/')
  })

  after(async function () {
    if (server) server.kill()
  })

  sharedTests()
})

describe('prod mode', function () {
  let server

  before(async function () {
    this.timeout(120000)
    await exec('npm run build')
    await exec('npm install', {
      cwd: path.join(__dirname, '../../build/meteor/bundle/programs/server'),
    })
    server = await launchAndWait('npm run prod', /App is listening on http/i)
    await browser.url('/')
  })

  after(async function () {
    if (server) server.kill()
  })

  sharedTests()
})


@@ -168,16 +168,74 @@
 m 'path'
+%0Aimport fs from 'fs'%0Aimport promisify from 'es6-promisify'
 %0A%0Aasync 
@@ -803,16 +803,17 @@
 function
+ 
 () %7B%0A   
@@ -897,32 +897,8 @@
 3')%0A
-      console.log(text)%0A
     
@@ -1383,32 +1383,32 @@
 er.kill()%0A  %7D)%0A%0A
-
   sharedTests()%0A
@@ -1402,24 +1402,706 @@
 haredTests()
+%0A%0A  it('supports hot reloading', async function () %7B%0A    this.timeout(20000)%0A    const appFile = path.resolve(__dirname, '../../src/universal/components/App.js')%0A    const appCode = await promisify(fs.readFile)(appFile, 'utf8')%0A    const newHeader = 'Welcome to Crater! with hot reloading'%0A    const modified = appCode.replace(/Welcome to Crater!/, newHeader)%0A    try %7B%0A      await promisify(fs.writeFile)(appFile, modified, 'utf8')%0A      await browser.waitUntil(%0A        () =%3E browser.getText('h1') === newHeader,%0A        10000,%0A        'expected header text to hot update within 10s'%0A      )%0A    %7D finally %7B%0A      await promisify(fs.writeFile)(appFile, appCode, 'utf8')%0A    %7D%0A  %7D)
 %0A%7D)%0A%0Adescrib

add hot reloading integration test