# Description:
#   interazioni tra asjon e git
#
# Dependencies:
#   None
#
# Configuration:
#   HUBOT_GIT_URL - git server url
#   HUBOT_GIT_API - git server API url
#   HUBOT_GIT_TOKEN - Gogs v1 or GitHub v3 API token
#   HUBOT_GIT_REPO - repository name (owner/repo)
# 
# Commands:
#   asjon mostra le issue - mostra le issue aperte su rnhmjoj/asjon
#
# Author:
#   Enrico Fasoli (fazo96)
#   Michele Guerini Rocco (rnhmjoj)

module.exports = (robot) ->
  githook = (req, res) ->
    res.send 200
    dest = name: req.params.name, room: id: req.params.room
    robot.emit 'githook', 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/githook/:room/:name?', githook

  robot.respond /(?:(?:mostra(?:mi)?|fammi vedere) )?(?:le )?issue(?:s)?/i, (res) ->
    msg = state: 'open', user: 'rnhmjoj', repo: 'asjon', sort: 'updated'
    res.send 'controllo issues...'
    url   = process.env.HUBOT_GIT_API
    repo  = process.env.HUBOT_GIT_REPO
    token = process.env.HUBOT_GIT_TOKEN

    if not token
      return res.send 'non ho il token per la repo'

    robot.http("#{url}/repos/#{repo}/issues?state=open&sort=updated")
         .header('Authorization', 'token '+token)
         .get() (err, r, body) ->
      if err then return res.send err
      data = JSON.parse body
      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) ->
    url  = process.env.HUBOT_GIT_URL
    repo = process.env.HUBOT_GIT_REPO
    base = "#{url}/#{repo}/issues/"
    res.send base+res.match[1]

  robot.respond /linkami (?:la )?repo (\w+\/\w+)/i, (res) ->
    url = process.env.HUBOT_GIT_URL
    res.send "#{url}/#{res.match[1]}/"

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