 pg = require("pg").native
 pg.defaults.poolSize = 5
 
-ok = (res, headers)->
-  for own k, v of headers
-    res.setHeader k, v
+ok = (res)->
   res.writeHead 200
 
 notfound = (res)->

    else
      events_since_id(channel, last_event_id, cb)

write_long_poll = (response, events, add_headers)->
  unless response.headersSent
    response.setHeader 'Content-Type', 'application/json'
    ok response, add_headers
  response.end JSON.stringify events
  false

write_eventsource = (response, events, add_headers)->
  unless response.headersSent
    response.setHeader 'Content-Type', 'text/event-stream'
    ok response, add_headers

  for event in events
    response.write ["event: "+event.data.type,
      "data: " + JSON.stringify(event.data.data),
      "id: " + event.id,
      "", ""].join "\n"

  true

waiting_channels = {}
listen_port = cfg.listen_port ? 9984
listen_address = cfg.listen_address ? '120.0.0.1'

exports.run = ->
  http.createServer((req, res)->

    req.on 'close', ->
      clear_waiting()

    handle_request = ()->
      handler channel, last_event_id, (err, evts)->
        return http_error res, 500, 'Failed to get event data: ' + err if err

        last_event_id = evts[evts.length-1].id if (evts and evts.length > 0)
        if waiting() or (evts and evts.length > 0)
          abort_processing = write(res, evts, not waiting());
          if abort_processing or waiting()
            res.end()
            return

        set_waiting()
        subscribe channel, (message)->
          handler channel, last_event_id, (err, evts)->
            return http_error 500, 'Failed to get event data' if err
            abort_processing = write res, evts, true
            return clear_waiting() if abort_processing
            last_event_id = evts[evts.length-1].id if (evts and evts.length > 0)
            process.nextTick ()->
              handle_request()
    handle_request()
  ).listen listen_port, listen_address

