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

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 + ')'


  run: ->
    self = @
    token = process.env.HUBOT_TALKER_TOKEN
    rooms = process.env.HUBOT_TALKER_ROOMS.split(',')

    bot = new TalkerClient()
    console.log bot

    ping = (room)->
      setInterval ->
        bot.write room, {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", (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 self.userForMessage(room, message), content

    bot.on "EnterMessage", (room, message) ->
      self.receive new Robot.EnterMessage self.userForMessage(room, message)

    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, "\\$&")
