const debug = require('debug')('loki:chrome:local');
const chromeLauncher = require('lighthouse/chrome-launcher/chrome-launcher');
const CDP = require('chrome-remote-interface');
const createChromeTarget = require('./create-chrome-target');

function createChromeAppTarget({
  baseUrl = 'http://localhost:6006',
  chromeFlags = ['--headless', '--disable-gpu', '--hide-scrollbars'],
}) {
  let instance;

  async function start(options = {}) {
    const launchOptions = Object.assign(
      {
        chromeFlags,
        logLevel: 'silent',
      },
      options
    );
    debug(
      `Launching chrome with flags "${launchOptions.chromeFlags.join(' ')}"`
    );
    instance = await chromeLauncher.launch(launchOptions);
  }

  async function stop() {
    if (instance) {
      debug('Killing chrome');
      // Do this woodoo to avoid some output that borks listr
      setTimeout(async () => {
        try {
          await instance.kill();
        } catch (err) {
          debug('Failed killing chrome', err);
        }
      }, 100);
    } else {
      debug('No chrome instance to kill');
    }
  }

  async function createNewDebuggerInstance() {
    const port = instance.port;
    debug(`Launching new tab with debugger at port ${port}`);
    const target = await CDP.New({ port });
    debug(`Launched with target id ${target.id}`);
    const client = await CDP({ port, target });

    client.close = () => {
      debug('New closing tab');
      return CDP.Close({ port, id: target.id });
    };

    return client;
  }

  return createChromeTarget(start, stop, createNewDebuggerInstance, baseUrl);
}

module.exports = createChromeAppTarget;

@@ -810,235 +810,28 @@
     
-// Do this woodoo to avoid some output that borks listr%0A      setTimeout(async () =%3E %7B%0A        try %7B%0A          await instance.kill();%0A        %7D catch (err) %7B%0A          debug('Failed killing chrome', err);%0A        %7D%0A      %7D, 100
+await instance.kill(
 );%0A 

Remove setTimeout voodoo that breaks closing chrome.app target on error