import * as genericPool from 'generic-pool'

import { config, logger } from '@things-factory/env'

try {
  var puppeteer = require('puppeteer')
} catch (err) {
  logger.error(err)
}

var headlessPool

export function getHeadlessPool() {
  if (!headlessPool) {
    headlessPool = genericPool.createPool(
      {
        create() {
          console.log('headless-pool-for-process about to create')
          return initializeChromium()
        },
        validate(browser) {
          return Promise.race([
            new Promise(res => setTimeout(() => res(false), 1500)),
            browser
              .version()
              .then(_ => true)
              .catch(_ => false)
          ])
        },
        destroy(browser) {
          return browser.close()
        }
      },
      {
        min: 2,
        max: 10,
        testOnBorrow: true,
        acquireTimeoutMillis: 15000
      }
    )
  }

  return headlessPool
}

const CHROMIUM_PATH = config.get('CHROMIUM_PATH')

async function initializeChromium() {
  try {
    if (!puppeteer) {
      return
    }

    var launchSetting = {
      args: ['--hide-scrollbars', '--mute-audio', '--no-sandbox', '--use-gl=egl'],
      headless: 'new'
    }

    if (CHROMIUM_PATH) {
      launchSetting['executablePath'] = CHROMIUM_PATH
    }

    const browser = await puppeteer.launch(launchSetting)

    return browser
  } catch (err) {
    logger.error(err)
  }
}
