# Description:
#   Queries whos on call from redis
#
# Commands:
#
#   hubot whos on call            lists the current on call
# Authors:
#   Steve Elliott


_ = require 'lodash'
moment = require 'moment'
redis = require 'redis';

client = redis.createClient(6379, process.env.HUBOT_ONCALL_REDIS, { max_attempts: 5 });  

client.on('ready', () ->
  console.log('Connected to redis store');
);

client.on('error', (err) -> 
  console.log('Redis Error: ' + err);
);

dayMap = {
  'today': 0,
  'tonight': 0
  'tomorrow': 1
}

module.exports = (robot) ->
  robot.hear /^hubot who(\'| i)?s on call (.+)$/i, (msg) ->
    day = msg.match[1]

    currentDay = moment().startOf 'day'
    start = moment(currentDay).hour(18)
    end = moment(currentDay).add(1, 'd').hour(8)

    msg.send "today starts: " + start.format()
    msg.send "today ends: " + end.format()

    client.hgetall 'oncallSchedule', (err, data) ->
      teamData = JSON.parse(data.teams)

      Object.keys(teamData).forEach (team) ->
        if team == 'everyone'
          return

        matchingScheduleItems = _.filter(teamData[team].schedule, (item) -> 
          itemStart = moment(item.start)
          itemEnd = moment(item.end)

          ((itemStart.isAfter start or itemStart.isSame start) and (itemEnd.isBefore end or itemEnd.isSame end))
        )

        console.log matchingScheduleItems

        # console.log team
        # console.log teamData[team].schedule

  robot.hear /^hubot who(\'| i)?s on call$/i, (msg) ->
    client.hgetall('oncallrota', (err, data) -> 
      returnedObj = JSON.parse data.oncall
      fields = _.map returnedObj, (entry) ->
        return {
          title: entry.team,
          value: entry.oncall
        }

      fallbackFields = fields.map (field) ->
        return field.title + ':' + field.value

      fallback = 'Current on call team is: \n' + (fallbackFields.join '\n')

      robot.emit 'slack-attachment', {
        channel: msg.message.room,
        attachments: [
          {
            title: 'Current On Call Team',
            fallback: fallback,
            color: 'good',
            fields: fields
          }
        ]
      }
    )
