 
   run: ->
     self = @
-    options =
-      token:   process.env.HUBOT_TALKER_TOKEN
-      rooms:   process.env.HUBOT_TALKER_ROOMS
+    token = process.env.HUBOT_TALKER_TOKEN
+    rooms = process.env.HUBOT_TALKER_ROOMS.split(',')
 
-    console.log options
-    bot = new TalkerClient(options)
+    bot = new TalkerClient()
     console.log bot
 
-    bot.connect ->
-      options.rooms.split(',').forEach (room) ->
-        console.log "Entering room: " + room
-        bot.write {"room": room, "token": options.token, "type": "connect"}
+    ping = (room)->
+      setInterval ->
+        bot.write room, {type: "ping"}
+      , 25000
 
-      setInterval ->
-        bot.write {type: "ping"}
-      , 25000
+    bot.on "Ready", (room)->
+      message = {"room": room, "token": token, "type": "connect"}
+      bot.write room, message
+      ping room
 
     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)
+    bot.on "TextMessage", (room, message)->
+      content = message.content
 
       # 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)
+      self.receive new Robot.TextMessage self.userForMessage(room, message), content
 
-    bot.on "EnterMessage", (message) ->
-      console.log message
-      author = self.userForId(message.user.id, message.user)
-      self.receive new Robot.EnterMessage(author)
+    bot.on "EnterMessage", (room, message) ->
+      self.receive new Robot.EnterMessage self.userForMessage(room, message)
 
-    bot.on "LeaveMessage", (message) ->
-      console.log message
-      author = self.userForId(message.user.id, message.user)
-      self.receive new Robot.LeaveMessage(author)
+    bot.on "LeaveMessage", (room, message) ->
+      self.receive new Robot.LeaveMessage self.userForMessage(room, message)
+
+    for room in rooms
+      bot.sockets[room] = bot.createSocket(room)
 
     @bot = bot
+
+  userForMessage: (room, message)->
+    author = @userForId(message.user.id, message.user)
+    author.room = room
+    author
 
   quoteRegex: (string) ->
     string.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")

module.exports = Talker

class TalkerClient extends EventEmitter
  constructor: (options) ->
    @token         = options.token
    @rooms         = options.rooms.split(",")
    @domain        = 'talkerapp.com'
    @encoding      = 'utf8'
    @port          = 8500

  connect: (callback) ->
    self = @

    @socket = tls.connect @port, @domain, ->
      # callback called only after successful socket socket
      console.log "Connected to " + self.domain
      self.socket.setEncoding @encoding
      callback()

    #callback
    @socket.addListener 'data', (data) ->
      for line in data.split '\n'
        console.log line

        message = unless line is ''
          message = JSON.parse(line)
        else
          message = null

        if message
          if message.type == "connected"
            self.emit "Connected"
          if message.type == "users"
            self.emit "Users", message
          if message.type == "message"
            self.emit "TextMessage", message
          if message.type == "join"
            self.emit "EnterMessage", message
          if message.type == "leave"
            self.emit "LeaveMessage", message
          if message.type == "error"
            self.disconnect message.message


    @socket.addListener "eof", ->
      console.log "eof"
    @socket.addListener "timeout", ->
      console.log "timeout"
    @socket.addListener "end", ->
      console.log "end"

  write: (arguments) ->
    self = @

    if @socket.readyState != 'open'
      return self.disconnect 'cannot send with readyState: ' + @socket.readyState

    message = JSON.stringify(arguments)
    console.log message

    @socket.write message, @encoding

  disconnect: (why) ->
    if @socket.readyState != 'closed'
      @socket.close
      console.log 'disconnected (reason: ' + why + ')'

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

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