# Author: VTEX

NodeCache = require 'node-cache'
request = require 'request'
FIVE_MINUTES = 5 * 60

class GetTags

  setCache = null

  constructor: (options) ->
    @options = options
    @cache = new NodeCache(stdTTL: FIVE_MINUTES)
    @cacheKey = "tags"
    @registryURL = options.registryURL ? "http://vtex-versioned-us.s3.amazonaws.com/registry/1/tags.json"


    setCache = (key, value, next) =>
      val = undefined
      if typeof value is 'string'
        try
          val = JSON.parse(value)
        catch e
          next e
      else
        val = value
      @cache.set key, val
      return val

  ########################
  # Handler              #
  ########################

  handler: (req, res, next) =>
    @options.logger?.debug('GetTags middleware')
    return next() if req.url.indexOf('/meta/whoami') is 0

    @cache.get @cacheKey, (err, val) =>
      if (err) then return console.error(err)
      if val is undefined or JSON.stringify(val) is '{}'
        
        request @registryURL, (err, res, body) =>
          return next(err) if err
          tags = setCache(@cacheKey, body, next)
          req.tags = tags
          next()
      else
        req.tags = val.tags
        next()

module.exports = GetTags
