# Author: VTEX

class OverduePaymentHandler

  SECONDS_VALUES = [5, 10, 15, 20]

  blockInterface = null
  getRandomValue = null

  constructor: (options) ->
    @options = options

    blockInterface = (options, req, res, next) ->
      cookieVal = new Date().toString()
      expireDate = new Date()
      expireDate.setMinutes(expireDate.getMinutes() + 5)
      cookieSettings =
        expires: expireDate
        httpOnly: true
      res.cookie('paymentPending', cookieVal, cookieSettings)
      res.set('Content-Type', 'text/html')
      res.render(options.view, options)

    getRandomValue = (collection) ->
      i = Math.floor(Math.random() * collection.length)
      return collection[i]

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

  handler: (req, res, next) =>
    @options.logger?.debug('OverduePaymentHandler middleware')
    return next() if req.url.indexOf('/meta/whoami') is 0
    return next() if not req.licenseManagerResponse?
    return next() if ((req.path.indexOf('admin/license-manager') isnt -1) or (req.path.indexOf('admin/billing') isnt -1))
    return next() if req.vtex.vtexIdData.user.split('@')[1] is 'vtex.com.br'

    options = {}

    try
      topbar = JSON.parse(req.licenseManagerResponse)
    catch e
      next(e)

    # if @options.splunkLogger
    #   @options.splunkLogger.logInfo('topbar', 'topbar on payment handler', JSON.stringify(topbar))

    # Gets user name
    if topbar.profile
      if topbar.profile.name
        options.userName = topbar.profile.name
      else
        options.userName = topbar.profile.email

    options.isBrazilianStore = true
    if (topbar.config.storeCountry and topbar.config.storeCountry.length)
      if (topbar.config.storeCountry  isnt "Brasil")
        options.isBrazilianStore = false

    # Blocks user if she has pending payment
    if topbar.config.paymentPending
      @options.logger?.info("Blocking access to #{req.vtex.store} due to pending payment")
      options.view = 'overduePaymentBlock'
      return blockInterface(options, req, res, next)

    # Sets a timed block page if user has a pending payment alert (level 2)
    if req.cookies.paymentPending and req.cookies.paymentPendingTimer
      setDate = new Date(decodeURIComponent(req.cookies.paymentPending))
      setDate.setSeconds(setDate.getSeconds() + parseInt(req.cookies.paymentPendingTimer))
      now = new Date()
      if (now.getTime() - setDate.getTime()) > req.cookies.paymentPendingTimer
        return next()

    # Renders timed block view
    if topbar.config.paymentPendingAlertTimer
      @options.logger?.warn("Temporarily blocking #{req.vtex.store} due to pending payment")
      options.seconds = getRandomValue(SECONDS_VALUES)
      options.view = 'overduePaymentTimer'
      res.cookie('paymentPendingTimer', options.seconds, { httpOnly: true })
      return blockInterface(options, req, res, next)

    next()

module.exports = OverduePaymentHandler
