'use strict';

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var puppeteer = require('puppeteer');
var page = void 0;
var browser = null;

var _require = require('../util/logger'),
    logger = _require.logger;

exports.launchHeadless = function () {
  var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(host, remotePort) {
    return _regenerator2.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return puppeteer.launch({
              // headless: false,
              args: ['--remote-debugging-port=' + remotePort, '--disable-gpu']
            });

          case 2:
            browser = _context.sent;

            logger.verbose('Headless has been launched');
            _context.next = 6;
            return browser.newPage();

          case 6:
            page = _context.sent;
            _context.next = 9;
            return page.goto('http://' + host + '/runtime.html');

          case 9:
            logger.verbose('Headless page goto http://' + host + '/runtime.html');

          case 10:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, undefined);
  }));

  return function (_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();

exports.closeHeadless = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2() {
  return _regenerator2.default.wrap(function _callee2$(_context2) {
    while (1) {
      switch (_context2.prev = _context2.next) {
        case 0:
          if (!page) {
            _context2.next = 3;
            break;
          }

          _context2.next = 3;
          return page.close();

        case 3:
          if (!browser) {
            _context2.next = 6;
            break;
          }

          _context2.next = 6;
          return browser.close();

        case 6:
          browser = null;
          logger.verbose('Cloased headless');

        case 8:
        case 'end':
          return _context2.stop();
      }
    }
  }, _callee2, undefined);
}));