/*
	Author: Kevin Saquing
	Filename: showMoreFromApi.js
	Description: 
	Dependencies:
		- B2C.handlebars
	How to use:
*/

;(function($) {
  "use strict"

  B2C.showMoreFromApi = {
    init: function(opts) {
      let _defaults = {
        url: "../public/data/moreProducts.json",
        template: "#showMoreTemplate",
        container: "#showMoreContainer",
        wrapper: "#showMoreWrapper",
        params: {
          count: 12,
          page: 1
        },
        button: "#showMore"
      }

      this._constructor = $.extend(_defaults, opts)

      if (!$(this._constructor.button).length) return

      this.events()
    },
    events: function() {
      let self = this
      let {
        button,
        url,
        template,
        container,
        wrapper,
        params: { count: count }
      } = self._constructor

      $(document).on("click", button, function() {
        // increment the page number everytime we add new data
        self._constructor.params.page += 1

        self.renderTemplate({
          url: url,
          target: template,
          container: container,
          wrapper: wrapper,
          data: {
            count: count,
            page: self._constructor.params.page
          },
          callback: function(data) {}
        })
      })
    },
    renderTemplate: async function(args) {
      let handlebarTemplate = Object.create(B2C.handlebar)
      let data = await this.getData({
        url: args.url,
        data: args.data || {}
      })

      handlebarTemplate.init({
        target: args.target,
        container: args.container,
        wrapper: args.wrapper,
        data: $.extend(true, data, args.extraData || {})
      })

      if ($.isFunction(args.callback)) args.callback(data)
    },
    getData: async function(args) {
      return new Promise(resolve => {
        $.ajax({
          url: args.url,
          data: args.data || {},
          dataType: "json",
          success: function(data) {
            resolve(data)
          }
        })
      })
    }
  }
})(jQuery)
