assert     = require 'assert'
path       = require 'path'
http       = require 'http'
url        = require 'url'
multiparty = require 'multiparty'

{remote} = require 'electron'
{app, crashReporter, BrowserWindow} = remote.require 'electron'

describe 'crash-reporter module', ->
  fixtures = path.resolve __dirname, 'fixtures'

  w = null
  beforeEach -> w = new BrowserWindow(show: false)
  afterEach -> w.destroy()

  # It is not working for mas build.
  return if process.mas

  # The crash-reporter test is not reliable on CI machine.
  isCI = remote.getGlobal('isCi')
  return if isCI

  it 'should send minidump when renderer crashes', (done) ->
    @timeout 120000
    called = false
    server = http.createServer (req, res) ->
      server.close()
      form = new multiparty.Form()
      form.parse req, (error, fields, files) ->
        # This callback can be called for twice sometimes.
        return if called
        called = true

        assert.equal fields['prod'], 'Electron'
        assert.equal fields['ver'], process.versions['electron']
        assert.equal fields['process_type'], 'renderer'
        assert.equal fields['platform'], process.platform
        assert.equal fields['extra1'], 'extra1'
        assert.equal fields['extra2'], 'extra2'
        assert.equal fields['_productName'], 'Zombies'
        assert.equal fields['_companyName'], 'Umbrella Corporation'
        assert.equal fields['_version'], app.getVersion()

        res.end('abc-123-def')
        done()
    # Server port is generated randomly for the first run, it will be reused
    # when page is refreshed.
    port = remote.process.port
    server.listen port, '127.0.0.1', ->
      {port} = server.address()
      remote.process.port = port
      url = url.format
        protocol: 'file'
        pathname: path.join fixtures, 'api', 'crash.html'
        search: "?port=#{port}"
      if process.platform is 'darwin'
        crashReporter.start
          companyName: 'Umbrella Corporation'
          submitURL: "http://127.0.0.1:#{port}"
      w.loadURL url

  describe ".start(options)", ->
    it 'requires that the companyName and submitURL options be specified', ->
      assert.throws(-> crashReporter.start({companyName: 'Missing submitURL'}))
      assert.throws(-> crashReporter.start({submitURL: 'Missing companyName'}))
