import { getHeadlessPool } from './headless-pool-for-process'
import { headlessModel } from './headless-model'
import { fonts } from './fonts'

const protocol = 'http'
const host = 'localhost'
const path = '/internal-process-service-view'

export const screenshot = async ({
  id = '',
  model = null,
  data = null,
  width: w = 0,
  height: h = 0,
  options = { encoding: 'base64' } as any,
  isThumbnail = false,
  context = {} as any
} = {}) => {
  const browser = (await getHeadlessPool().acquire()) as any
  var screenshot = null

  if (!browser) {
    return
  }
  const { domain, user } = context.state

  var { model, base } = await headlessModel({ domain, id, model })
  model.fonts = await fonts()

  var { width, height } = model

  if (isThumbnail) {
    var widthRatio = 400 / width,
      heightRatio = 300 / height
    var ratio = widthRatio < heightRatio ? widthRatio : heightRatio
    width = width * ratio
    height = height * ratio
  }
  width = Math.floor(w || Number(width))
  height = Math.floor(h || Number(height))

  const port = process.env.PORT ? `:${process.env.PORT}` : ''
  const url = `${protocol}://${host}${port}${path}`

  var page = await browser.newPage()

  try {
    /* @remember-me width, height should be a integer */
    await page.setViewport({ width, height })
    await page.setRequestInterception(true)
    await page.setDefaultTimeout(5000)

    page.on('console', msg => {
      console.log(`[browser ${msg._type}] ${msg._text}`)
      for (let i = 0; i < msg.args().length; ++i) console.log(`${i}: ${msg.args()[i]}`)
    })

    const token = await user?.sign() // TODO improve performance

    page.on('request', request => {
      if (request.url() === url) {
        request.continue({
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'x-things-factory-domain': domain?.subdomain,
            Authorization: 'Bearer ' + token
          },
          postData: JSON.stringify({
            model,
            base
          })
        })
      } else if (request.url().startsWith(`${protocol}://${host}${port}`)) {
        request.continue({
          headers: {
            ...request.headers(),
            'x-things-factory-domain': domain?.subdomain,
            Authorization: 'Bearer ' + token
          }
        })
      } else {
        request.continue()
      }
    })
    await page.goto(url)

    await page.evaluate(async data => {
      if (data) {
        // @ts-ignore
        s.data = data
      }

      // data 주입 후 강제 지연시킴.
      return new Promise(resolve => {
        // @ts-ignore
        requestAnimationFrame(() => resolve())
      })
    }, data)

    screenshot = await page.screenshot(options)
  } catch (error) {
    console.log(error)
  } finally {
    page.close()
    getHeadlessPool().release(browser)
  }

  return screenshot
}
