$ = jQuery
context = window
context.JK ||= {};

class CheckoutUtils
  constructor: () ->
    @logger = context.JK.logger
    @rest = new context.JK.Rest();
    @cookie_name = "preserve_billing"
    @lastPurchaseResponse = null
    @configuredRecurly = false

  init: () =>

  refreshPreserveBillingInfo:() =>
    if @shouldPreserveBillingInfo
      @logger.debug("refreshing preserve billing info timer")
      @setPreserveBillingInfo()

  setPreserveBillingInfo:() =>
    date = new Date();
    minutes = 10;
    date.setTime(date.getTime() + (minutes * 60 * 1000))
    $.removeCookie(@cookie_name, { path: '/' })
    $.cookie(@cookie_name, "jam", { expires: date, path: '/' })

  deletePreserveBillingInfo:() =>
    $.removeCookie(@cookie_name, { path: '/' })

    @logger.debug("deleted preserve billing");

    if $.cookie(@cookie_name)?
      @logger.error("after deleting the preserve billing cookie, it still exists!")


  # existance of cookie means we should preserve billing
  shouldPreserveBillingInfo:() =>
    value = $.cookie(@cookie_name)
    value?

  setLastPurchase: (purchaseResponse) =>
    @lastPurchaseResponse = purchaseResponse

  getLastPurchase: () =>
    return @lastPurchaseResponse

  hasOneFreeItemInShoppingCart: (carts) =>

    if carts.length == 0
      # nothing is in the user's shopping cart.  They shouldn't be here.
      return false;
    else if carts.length > 1
      # the user has multiple items in their  shopping cart.  They shouldn't be here.
      return false;

    return carts[0].product_info.free

  hasOnlyFreeItemsInShoppingCart: (carts) =>
    if carts.length == 0
      return false

    for cart in carts
      if !cart.product_info.free
        return false

    return true

  configureRecurly: () =>
    unless window.configuredRecurly
      context.recurly.configure(gon.global.recurly_public_api_key)
      window.configuredRecurly = true

# global instance
context.JK.CheckoutUtilsInstance = new CheckoutUtils()