//from https://github.com/makinacorpus/django-screamshot

const puppeteer = require('puppeteer');

function delay(time) {
    return new Promise(function(resolve) { 
        setTimeout(resolve, time)
    });
 }

/** 
 * arguments:
 * [1] => URL
 * [2] => output. Use /dev/stdout if you want to capture.
 * [3] => size
 */

var address = process.argv[2],
    output  = process.argv[3];

config = {}
process.argv.forEach(function(arg, i) {
    if (i > 3) {
        namev = arg.split('=');
        config[namev[0].replace('--', '')] = namev[1];
    }
});

const width = parseInt(config.width || 1920),
      height = parseInt(config.height || 1080),
      wait = parseInt(config.wait || 1080);

(async () => {
  const browser = await puppeteer.launch({
      defaultViewport: {width: width, height: height},
      ignoreHTTPSErrors: true,
  });
  const page = await browser.newPage();
  await page.goto(address, {waitUntil: 'domcontentloaded'});
  // Wait until page has loaded completely
  await delay(wait);
  // Make a screenshot
  await page.screenshot({path: output});

  await browser.close();
})();