_             = require("lodash")
App           = require("electron").app
BrowserWindow = require("electron").BrowserWindow
crashReporter = require("electron").crashReporter
Args          = require("./args")

## Keep a global reference of the window object, if you don't, the window will
## be closed automatically when the JavaScript object is garbage collected.
mainWindow = null

module.exports = (argv) ->
  crashReporter.start({
    productName: "Chromium"
    companyName: "Cypress"
    submitURL: "https://clxiuqckik.localtunnel.me/crash"
  })

  ## parse the process.argv
  options = Args(argv)

  ## just output our version + quit
  ## if we've passed the version flag
  if options.version
    process.stdout.write(App.getVersion() + "\n")
    return process.exit(0)

  console.log(process.env)

  ## if we dont have a url then exit
  if not options.url
    process.stdout.write("No 'url' specified. Exiting.\n")
    return process.exit(1)

  ## if we are remote debugging then
  ## add the command line flag to the
  ## specified remote debugging port
  if options.remoteDebugging
    App.commandLine.appendSwitch("remote-debugging-port", options.remoteDebuggingPort)

  ## Quit when all windows are closed.
  App.on "window-all-closed", ->
    App.quit()

  ## This method will be called when Electron has finished
  ## initialization and is ready to create browser windows.
  App.on "ready", ->
    ## Create the browser window.
    mainWindow = new BrowserWindow({
      width: 1280
      height: 720
      ## "type": "toolbar"
      show: true#options.display
      webPreferences: {
        nodeIntegration: false
        pageVisibility: true
        allowDisplayingInsecureContent: true
        allowRunningInsecureContent: true
      }
    })


    # mainWindow.webContents.on "did-fail-load", (event, errorCode, errorDescription, validatedUrl) ->
    #   process.stderr.write(JSON.stringify({
    #     errorCode: errorCode
    #     errorDescription: errorDescription
    #   }))

    #   ## exit with process.exit(1)
    #   process.exit(1)

    ## and load the index.html of the App.
    mainWindow.loadURL(options.url)

    ## Open the DevTools conditionally
    if options.devTools
      mainWindow.webContents.openDevTools()

    mainWindow.on "unresponsive", ->
      process.stdout.write("-----------window became unresponsive----------")

    ## Emitted when the window is closed.
    mainWindow.on "closed", ->
      ## Dereference the window object, usually you would store windows
      ## in an array if your app supports multi windows, this is the time
      ## when you should delete the corresponding element.
      mainWindow = null
