/* eslint-env jest */

import {
  findPort,
  killApp,
  launchApp,
  nextBuild,
  nextStart,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'

const appDir = join(__dirname, '../')

let appPort
let app

function runTests(url: string) {
  it('should work with loaderFile config, leaving default image optimization enabled', async () => {
    const browser = await webdriver(appPort, url)
    expect(await browser.elementById('img1').getAttribute('src')).toBe(
      '/_next/image/?url=/logo.png&w=828&q=50'
    )
    expect(await browser.elementById('img1').getAttribute('srcset')).toBe(
      '/_next/image/?url=/logo.png&w=640&q=50 1x, /_next/image/?url=/logo.png&w=828&q=50 2x'
    )

    // make sure the image was indeed successfully loaded from /_next/image
    expect(
      await browser.eval(
        `document.getElementById('img1').complete && document.getElementById('img1').naturalWidth !== 0`
      )
    ).toBe(true)
  })

  it('should work with loader prop', async () => {
    const browser = await webdriver(appPort, url)
    expect(await browser.elementById('img2').getAttribute('src')).toBe(
      '/logo.png?wid=640&qual=35'
    )
    expect(await browser.elementById('img2').getAttribute('srcset')).toBe(
      '/logo.png?wid=256&qual=35 1x, /logo.png?wid=640&qual=35 2x'
    )
  })
}

describe('Image Loader Config', () => {
  describe('dev mode - component', () => {
    beforeAll(async () => {
      appPort = await findPort()
      app = await launchApp(appDir, appPort)
    })
    afterAll(() => {
      killApp(app)
    })
    runTests('/')
  })

  describe('server mode - component', () => {
    beforeAll(async () => {
      await nextBuild(appDir)
      appPort = await findPort()
      app = await nextStart(appDir, appPort)
    })
    afterAll(() => {
      killApp(app)
    })
    runTests('/')
  })
  describe('dev mode - getImgProps', () => {
    beforeAll(async () => {
      appPort = await findPort()
      app = await launchApp(appDir, appPort)
    })
    afterAll(() => {
      killApp(app)
    })
    runTests('/get-img-props')
  })

  describe('server mode - getImgProps', () => {
    beforeAll(async () => {
      await nextBuild(appDir)
      appPort = await findPort()
      app = await nextStart(appDir, appPort)
    })
    afterAll(() => {
      killApp(app)
    })
    runTests('/get-img-props')
  })
})
