 #
 # Configuration:
 #   HUBOT_SPOT_URL
+#   HUBOT_SPOT_MENTION_ROOM
 #
 # Commands:
 #   hubot play! - Plays current playlist or song.

  robot.respond /respot/i, (message) ->
    spotRequest message, '/respot', 'put', {}, (err, res, body) ->
      message.send(body)



    if (err)
      message.send(":flushed: " + err)

queueTrack = (track, qL, message) ->
  unless track && track.uri
    message.send("Sorry, couldn't add that to the queue")
    return
  qL.push track
  message.send(":small_blue_diamond: I'm adding " + track.name + " to the queue")
  message.send "Current queue: #{qL.length} songs"

playNextTrackInQueue = (robot) ->
  track = robot.brain.data.ql.shift()
  robot.messageRoom(MENTION_ROOM, "Switching to " + track.name)
  robot.http(URL+'/play-uri')
    .query({'uri' : track.uri})['post']() (err,res,body) ->
      if (err)
        console.log "Error playing Queued Track" + err
      sleep(4000) # hacky but otherwise sometimes it plays two tracks in a row

sleep = (ms) ->
  start = new Date().getTime()
  continue while new Date().getTime() - start < ms

module.exports = (robot) ->

  playQueue = (robot) ->
    if robot.brain.data.ql && robot.brain.data.ql.length > 0
      robot.http(URL+'/seconds-left')
        .get() (err, res, body) ->
          seconds_left = parseFloat(body)
          if seconds_left < 3
            playNextTrackInQueue(robot)
    setTimeout (->
      playQueue(robot)
    ), 1000

  playQueue(robot)

  robot.respond /queue list/i, (message) ->
    queue_list = []
    if robot.brain.data.ql.length > 0
      for track in robot.brain.data.ql
        queue_list.push(track.name)
      message.send "Current Queue: #{queue_list.join(', ')}"
    else
      message.send "Nothing queued up."

  robot.respond /clear queue/i, (message) ->
    robot.brain.data.ql = []
    message.send "Queue cleared"

  robot.respond /queue (.*)/i, (message) ->
    robot.brain.data.ql ?= []
    qL = robot.brain.data.ql
    playNum = message.match[1].match(/#(\d+)\s*$/)
    if (playNum)
      r = getLastResultsRelevantToUser(robot, message.message.user)
      i = parseInt(playNum[1], 10) - 1
      if (r && r[i])
        queueTrack(r[i], qL, message)
        return

  robot.respond /play!/i, (message) ->
    message.finish()
