var electron = require('electron')
var Convert = require('ansi-to-html')
var convert = new Convert()
var Cucumber = require('cucumber')

// HACK:
// window.Gherkin !== require('gherkin') in browsers, so parsing fails unless:
require('gherkin').Parser = window.Gherkin.Parser
require('gherkin').Compiler = window.Gherkin.Compiler
require('gherkin').DIALECTS = window.Gherkin.DIALECTS

var cli = require('./cli')(electron.remote.process.argv)

var stdout = electron.remote.process.stdout

function log() {
  var args = [].slice.apply(arguments)
  stdout.write.apply(null, args)
  var output = convert.toHtml(args[0].toString(), { fg: '#000', bg: '#fff' })
  var pre = document.createElement('pre')
  pre.innerHTML = output
  document.body.appendChild(pre)
}

var PrettyFormatter = Cucumber.Listener.PrettyFormatter
Cucumber.Listener.PrettyFormatter = function(options) {
  options.logToFunction = log
  return PrettyFormatter(options)
}

var args = JSON.parse(decodeURIComponent(window.location.hash.substr(1)))

var cucumberCli = Cucumber.Cli([`${__dirname}/node_modules/.bin/cucumberjs`, __dirname].concat(args));

function exitWithCode(code) {
  if (cli.electronDebug) return
  electron.remote.process.exit(code)
}

try {
  cucumberCli.run(function(succeeded) {
    exitWithCode(succeeded ? 0 : 1)
  });
} catch (err) {
  log(err.stack)
  exitWithCode(2)
}

@@ -1347,12 +1347,270 @@
 thCode(2)%0A%7D%0A
+%0Adocument.body.addEventListener(%22keydown%22, function(e) %7B%0A  e = e %7C%7C window.event;%0A  var key = e.which %7C%7C e.keyCode;%0A  var ctrl = e.ctrlKey ? e.ctrlKey : ((key === 17) ? true : false);%0A  if ( key == 67 && ctrl ) %7B electron.remote.process.exit(0) %7D%0A%7D, false);%0A

Exit process on ctrl + c