# Author: VTEX

fs = require 'fs'
request = require 'request'

class ResolveTemplate

  constructor: (options) ->
    @options = options

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

  handler: (req, res, next) =>
    @options.logger?.debug('RenderTemplate middleware')
    return next() if @options.utils.isAdmin(req, @options) is false
    return next() if req.url.indexOf('/admin/logout') isnt -1 or req.url.indexOf('/admin/login') isnt -1
    return next() if req.template?

    defaultPath = @options.customPath or "build/#{req.cleanUrl}/index.dust"

    try
      @options.logger?.info 'Trying to read file', defaultPath
      req.template = fs.readFileSync defaultPath, 'utf-8'
    catch err
      return next(new Error("Caught the following error when trying to read the file #{defaultPath}: #{err.message}"))

    return next()

module.exports = ResolveTemplate
