const puppeteer = require('puppeteer-extra')
const StealthPlugin = require('puppeteer-extra-plugin-stealth')

puppeteer.use(StealthPlugin())

module.exports = class Pptr {
    static browser = null

    static async init(options = {}) {
        if (this.browser) return this.browser

        this.browser = await puppeteer.launch({
            headless: false,
            args: ['--no-sandbox', '--disable-setuid-sandbox'],
            ...options,
        })

        this.browser.on('disconnected', () => {
            this.browser = null
        })

        return this.browser
    }

    static async newPage() {
        if (!this.browser) {
            await this.init()
        }
        const page = await this.browser.newPage()
        await page.setViewport({ width: 1366, height: 768 })
        return page
    }

    static async close() {
        if (this.browser) {
            await this.browser.close()
            this.browser = null
        }
    }
}
