# Description:
#   Doge meme generator
#   Requires hubot-tg adapter to access message history
#
# Configuration:
#   Uses hubot-tg enviroment variables
#
# Commands
#   hubot doge [n] - crea un meme doge con messaggi recenti della chat
#
# Author:
#   Michele Guerini Rocco (rnhmjoj)
#


net = require 'net'

module.exports = (robot) ->
  run_command = (command, callback) ->
    client = net.connect robot.adapter.port, robot.adapter.host, ->
      client.write command+'\n'
    client.setEncoding 'utf8'
    client.on 'data', (reply) ->
      if callback?
        callback (reply.split '\n')[1..-3]
      client.end()

  get_history = (chat, size, callback) ->
    regex = /^(?:\d+ )?\[(.+)\] (.+) [»«><]+ (.+)/
    parse_line = (x) ->
      date: x[1]
      peer: x[2].replace chat + ' ', ''
      text: x[3].trim()
    run_command "history #{chat} #{size}", (lines) ->
      callback (parse_line i.match regex for i in lines.split '\n')

  robot.respond /doge(?: (\d+))?/, (res) ->
    n = res.match[1] || 10
    get_history res.message.room, n, (history) ->
      words  = [].concat (message.text.split() for message in history)
      sample = res.random words for _ in [0..5]
      #do doge meme with sample