 module.exports = Talker
 
 class TalkerClient extends EventEmitter
-  constructor: (options) ->
-    @token         = options.token
-    @rooms         = options.rooms.split(",")
+  constructor: ->
     @domain        = 'talkerapp.com'
     @encoding      = 'utf8'
     @port          = 8500
+    @sockets       = {}
 
-  connect: (callback) ->
+  createSocket: (room) ->
     self = @
 
-    @socket = tls.connect @port, @domain, ->
-      # callback called only after successful socket socket
-      console.log "Connected to " + self.domain
-      self.socket.setEncoding @encoding
-      callback()
+    socket = tls.connect @port, @domain, ->
+      console.log("Connected to room #{room}.")
+      self.emit "Ready", room
 
     #callback
-    @socket.addListener 'data', (data) ->
+    socket.on 'data', (data) ->
       for line in data.split '\n'
-        console.log line
-
-        message = unless line is ''
-          message = JSON.parse(line)
-        else
-          message = null
+        message = if line is '' then null else JSON.parse(line)
 
         if message
-          if message.type == "connected"
-            self.emit "Connected"
+          console.log "From room #{room}: #{line}"
           if message.type == "users"
             self.emit "Users", message
           if message.type == "message"
-            self.emit "TextMessage", message
+            self.emit "TextMessage", room, message
           if message.type == "join"
-            self.emit "EnterMessage", message
+            self.emit "EnterMessage", room, message
           if message.type == "leave"
-            self.emit "LeaveMessage", message
+            self.emit "LeaveMessage", room, message
           if message.type == "error"
-            self.disconnect message.message
+            self.disconnect room, message.message
 
-
-    @socket.addListener "eof", ->
+    socket.addListener "eof", ->
       console.log "eof"
-    @socket.addListener "timeout", ->
+    socket.addListener "timeout", ->
       console.log "timeout"
-    @socket.addListener "end", ->
+    socket.addListener "end", ->
       console.log "end"
 
-  write: (arguments) ->
+    socket.setEncoding @encoding
+
+    socket
+
+  write: (room, arguments) ->
     self = @
+    @sockets[room]
 
-    if @socket.readyState != 'open'
-      return self.disconnect 'cannot send with readyState: ' + @socket.readyState
+    if @sockets[room].readyState != 'open'
+      return @disconnect 'cannot send with readyState: ' + @sockets[room].readyState
 
     message = JSON.stringify(arguments)
-    console.log message
+    console.log "To room #{room}: #{message}"
 
-    @socket.write message, @encoding
+    @sockets[room].write message, @encoding
 
-  disconnect: (why) ->
-    if @socket.readyState != 'closed'
-      @socket.close
+  disconnect: (room, why) ->
+    if @sockets[room] != 'closed'
+      @sockets[room]
       console.log 'disconnected (reason: ' + why + ')'


  run: ->
    self = @
    options =
      token:   process.env.HUBOT_TALKER_TOKEN
      rooms:   process.env.HUBOT_TALKER_ROOMS

    console.log options
    bot = new TalkerClient(options)
    console.log bot

    bot.connect ->
      options.rooms.split(',').forEach (room) ->
        console.log "Entering room: " + room
        bot.write {"room": room, "token": options.token, "type": "connect"}

      setInterval ->
        bot.write {type: "ping"}
      , 25000

    bot.on "Users", (message)->
      for user in message.users
        self.userForId(user.id, user)

    bot.on "TextMessage", (message)->
      console.log message

      author = self.userForId(message.user.id, message.user)

      # Replace "@mention" with "mention: ", case-insensitively
      regexp = new RegExp("\\b@#{self.quoteRegex(self.name)}\\b", 'i')
      content = message.content.replace(regexp, "#{self.name}: ")

      self.receive new Robot.TextMessage(author, content)

    bot.on "EnterMessage", (message) ->
      console.log message
      author = self.userForId(message.user.id, message.user)
      self.receive new Robot.EnterMessage(author)

    bot.on "LeaveMessage", (message) ->
      console.log message
      author = self.userForId(message.user.id, message.user)
      self.receive new Robot.LeaveMessage(author)

    @bot = bot

  quoteRegex: (string) ->
    string.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")

class Talker extends Robot
  send: (user, strings...) ->
    strings.forEach (str) =>
      @bot.write user.room, {"type": "message", "content": str}

  reply: (user, strings...) ->
    strings.forEach (str) =>
