const puppeteer = require('puppeteer');

const launch = async (
  config = { url: '', screenshotPath: '', executablePath: '', timeout: 1000 }
) => {

  config = Object.assign({
    url: 'https://scrapingbee.com',
    screenshotPath: './screenshot.jpg',
    executablePath: '/usr/bin/chromium',
    timeout: 1000,
  }, config)

  const profile = {
    data: [
      // 'wormlazy199210',
      'wormlazy199211',
      'wormlazy199212',
    ],
    select: function() {
      return this.data[Math.floor(Math.random() * this.data.length)]
    }
  }

  const browser = await puppeteer.launch({
    executablePath: config.executablePath,
    args: [
      '--no-sandbox',
      '--headless',
      '--disable-gpu',
      `--user-data-dir=/puppeteer/chrome-profiles/${profile.select()}`
    ]
  });
  const page = await browser.newPage();

  // Set the viewport's width and height
  await page.setViewport({ width: 1920, height: 1080 });

  // Open ScrapingBee's home page
  await page.goto(config.url);

  // Waiting Dom Ready
  await new Promise(r => setTimeout(r, config.timeout));

  try {
    // Capture screenshot and save it in the current folder:
    await page.screenshot({ path: config.screenshotPath });
    console.log(`Screenshot has been captured successfully`);

  } catch (err) {
    console.log(`Error: ${err.message}`);
  } finally {
    await browser.close();
  }
};
module.exports = launch
