 HTTPS = require 'https'
 
 class Slack extends Adapter
+  log: console.log.bind console
+  logError: console.error.bind console
+
   send: (params, strings...) ->
-    console.log "Sending message"
+    @log "Sending message"
 
     user = @userFromParams(params)
 
     strings.forEach (str) =>
-      # Escape this
-      str = str.replace(/&/g, '&amp;')
-      str = str.replace(/</g, '&lt;')
-      str = str.replace(/>/g, '&gt;')
-
-      # Linkify. We assume that the bot is well-behaved and
-      # consistently sending links with the protocol part
-      str = str.replace(/((\bhttp)\S+)/g, '<$1>')
+      str = @escapeHtml str
 
       args = JSON.stringify({"channel": user.reply_to, "text": str, username: @robot.name})
       @post "/services/hooks/hubot", args
 
   reply: (params, strings...) ->
-    console.log "Sending reply"
+    @log "Sending reply"
 
     user = @userFromParams(params)
     strings.forEach (str) =>


    params

  run: ->
    self = @

    @options =
      token:   process.env.HUBOT_SLACK_TOKEN or null
      team:    process.env.HUBOT_SLACK_TEAM or null
      name:    process.env.HUBOT_SLACK_BOTNAME or 'slackbot'
    console.log "Slack adapter options:", @options

    unless @options.token
      console.error "No services token provided to Hubot"
      return

    unless @options.team
      console.error "No team provided to Hubot"
      return

    # Listen to incoming webhooks from slack
    self.robot.router.post "/hubot/slack-webhook", (req, res) ->
      console.log "Incoming message received"

      # Parse the payload
      from = req.param('user_id')
      from_name = req.param('user_name')
      channel = req.param('channel_id')
      channel_name = req.param('channel_name')
      hubot_msg = req.param('text')

      if hubot_msg
        # Convert markup into plain url string.
        hubot_msg = hubot_msg.replace(/<((\bhttps?)[^|]+)(\|(.*))+>/g, '$1')
        hubot_msg = hubot_msg.replace(/<((\bhttps?)(.*))?>/g, '$1')

        # Unescape
        hubot_msg = hubot_msg.replace(/&amp;/g, '&')
        hubot_msg = hubot_msg.replace(/&lt;/g, '<')
        hubot_msg = hubot_msg.replace(/&gt;/g, '>')

        # Construct an author object
        author = {}
        author.id = from
        author.name = from_name
        author.reply_to = channel
        author.room = channel_name

        # Pass to the robot
        console.log "Received #{hubot_msg} from #{author.name}"
        self.receive new TextMessage(author, hubot_msg)

      # Just send back an empty reply, since our actual reply,


      response.on "end", ->
        if response.statusCode >= 400
          self.logError "Slack services error: #{response.statusCode}"
          self.logError data

        #console.log "HTTPS response:", data
        if callback
          callback null, data

        response.on "error", (err) ->
          self.logError "HTTPS response error:", err
          if callback
            callback err, null

