+net = require 'net'
 fs = require 'fs'
 path = require 'path'
 optimist = require 'optimist'

  sendCommand: (command) ->
    atomWindow.sendCommand command for atomWindow in @windows when atomWindow.browserWindow.isFocused()

  open: (pathToOpen = '') ->
    pathToOpen = path.resolve(executedFrom, pathToOpen) if executedFrom

    atomWindow = new AtomWindow
      pathToOpen: pathToOpen
      bootstrapScript: 'window-bootstrap',
      resourcePath: @resourcePath

    @windows.push atomWindow

  runSpecs: ->
    specWindow = new AtomWindow

    resourcePath = path.dirname(__dirname)

bootstrapApplication = ->
  setupNodePath()
  atomApplication = new AtomApplication({resourcePath, executedFrom})
  atomApplication.open(pathsToOpen)

delegate.browserMainParts.preMainMessageLoopRun = ->
  client = null
  socketPath = '/tmp/atom.sock'

  parseCommandLine()

  connect = (callback) ->
    client = net.connect {path: socketPath}, (args...) ->
      output = JSON.stringify({pathsToOpen: pathsToOpen})
      client.write(output)
      callback(true)

    client.on 'error', (args...) ->
      console.log 'error', args
      callback(false)

  listen = ->
    fs.unlinkSync socketPath if fs.existsSync(socketPath)
    server = net.createServer (connection) ->
      connection.on 'data', (data) ->
        { pathsToOpen } = JSON.parse(data)
        atomApplication.open(pathsToOpen)

    server.listen socketPath
    server.on 'error', (error) -> console.error 'Application server failed', error

  connect (success) ->
    if success
      process.exit(1)
    else
      listen()
      bootstrapApplication()

BrowserWindow = require 'browser_window'
Menu = require 'menu'
