# Description:
#   interazioni tra asjon e github
#
# Requires:
#   "github": "0.2.4"
#
# Commands:
#   asjon mostra le issue - mostra le issue aperte su fazo96/asjon
#
# Author:
#   Enrico Fasoli (fazo96)

GitHubAPI = require 'github'
github = new GitHubAPI version: '3.0.0'

module.exports = (robot) ->
  githubhook = (req, res) ->
    res.send 200
    dest = name: req.params.name, room: req.params.room.replace(':','#')
    robot.emit 'githubhook', req.body, req.params
    s = 'Branch '+req.body.ref+' aggiornato!\n'
    cm = req.body.commits.map (c) ->
      [c.committer.username,c.message].join ' -> '
    robot.send dest, s+cm.join('\n')

  unless process.env.TESTING_ASJON
    # Disabilito http route durante i test
    robot.router.post '/hubot/githubhook/:room/:name?', githubhook

  robot.respond /(?:(?:mostra(?:mi)?|fammi vedere) )?(?:le )?issue(?:s)?/i, (res) ->
    msg = state: 'open', user: 'fazo96', repo: 'asjon', sort: 'updated'
    res.send 'controllo issues...'
    github.issues.repoIssues msg, (err,data) ->
      if err then return res.send err
      if data.length is 0 then return res.send '0 issues'
      r = data.map (i) ->
        labels = i.labels.map((x) -> x.name).join ', '
        if labels is '' then labels = 'nessuno'
        ["#"+i.number,i.title,"By: "+i.user.login,'Tags: '+labels].join(' | ')
      res.send r.join '\n'

  robot.respond /linkami (?:la )?issue (?:(?:n(?:°)?(?: )?)|numero )?(\d+)/i, (res) ->
    base = 'http://github.com/fazo96/asjon/issues/'
    res.send base+res.match[1]

  robot.respond /linkami (?:la )?repo (\w+\/\w+)/i, (res) ->
    res.send 'https://github.com/'+res.match[1]

  # rendo l'handler dell'hook di github accessibile
  # in caso serve (nei test)
  return githubhook