/*
	Author: Jeremy Espinosa
	Filename: banner.js
	Description: This change the background according to given image for desktop, tablet and mobile
	Dependencies:
		- utils/slick.js
		- utils/currentWindow.js
		- underscore - this is use for debounce
		- slick-carousel
	How to use:
		1. Check the banner component html
		2. Pass parameters to the initialization of the banner
			- target = this the parent of the banner
			- backgroundImage - holds the image for desktop, tablet and mobile
*/

;(function($) {
  "use strict"

  B2C.banner = {
    init: function(option) {
      // set default
      this._default = {
        target: ".js-banner-slick",
        backgroundImage: ".banner__image-holder"
      }

      // combine the default and option pass
      this._option = $.extend({}, this._default, option)

      if (!$(this._option.target).length) return

      // initialize to get the current window
      B2C.currentWindow.init()

      // check window resize then change the background depends on it
      this.windowResize()
      // change the background on load depends on the breakpoint
      this.changeBackground(this.getBackgroundImage(this))
    },

    windowResize: function() {
      const self = this
      window.addEventListener(
        "resize",
        _.debounce(function() {
          // get the background for mobile, tablet, desktop
          self.changeBackground(self.getBackgroundImage(self))
        }, 300)
      )
    },

    getBackgroundImage: function(self) {
      let desktop = "",
        tablet = "",
        mobile = "",
        backgroundImageArray = []

      $(self._option.backgroundImage).each(function() {
        desktop = $(this).data("bg-desktop")
        tablet = $(this).data("bg-tablet")
        mobile = $(this).data("bg-mobile")

        // change the background every loop
        backgroundImageArray.push({
          target: this,
          desktop,
          tablet,
          mobile
        })
      })

      return backgroundImageArray
    },

    changeBackground: function(options) {
      let breakpoint = B2C.currentWindow.getBreakpoint(),
        backgroundImage = ""

      options.map(option => {
        // set the background depends on the breakpoint
        if (breakpoint === "mobile") backgroundImage = option.mobile
        else if (breakpoint === "tablet") backgroundImage = option.tablet
        else backgroundImage = option.desktop

        // change the background image
        $(option.target).css({
          backgroundImage: `url(${backgroundImage})`
        })
      })
    }
  }

  // initialize banner
  const defaultBanner = Object.create(B2C.banner)

  //   defaultBanner.init()
})(jQuery)
