const puppeteer = require('puppeteer-cn')
let page
let browser = null
const {
  logger
} = require('../util')

exports.launchHeadless = async (host, remotePort) => {
  const options = {
    args: [`--remote-debugging-port=${remotePort}`, `--disable-gpu`]
  }
  if (process.PUPPETEER_EXECUTABLE_PATH) {
    options.executablePath = process.PUPPETEER_EXECUTABLE_PATH
    options.args.push(`--url=http://${host}/runtime/runtime.html`)
  }
  browser = await puppeteer.launch(options)
  logger.info(`pid=${browser.process().pid}`)
  logger.verbose(`Headless has been launched`)
  if (!process.PUPPETEER_EXECUTABLE_PATH) {
    page = await browser.newPage()
    await page.setUserAgent(
      '5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
    )
    await page.goto(`http://${host}/runtime/runtime.html`)
    logger.verbose(`Headless page goto http://${host}/runtime/runtime.html`)
  }
}

exports.closeHeadless = async () => {
  if (page) {
    await page.close()
  }
  if (browser) {
    await browser.close()
  }
  browser = null
  logger.verbose(`Cloased headless`)
}
