/*
Author: Thelma Suyam
Filename: catalog-filter.js
Description:
Dependencies:
How to use:
*/
;(function($) {
  "use strict"

  B2C.catalogFilter = {
    init: function(option) {
      this._default = {
        target: ".js-product-items",
        colorPicker: ".js-colorpicker",
        priceFilter: ".js-filter-price",
        pagination: ".js-catalog-pagination",
        layoutView: "grid"
      }

      this._option = $.extend({}, this._default, option)

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

      this.onloadTemplate()
      this.eventListener()
    },

    eventListener: function() {
      const self = this

      // form
      $(document).on("change submit", "#filterForm", function(e) {
        self.reloadTemplate(self, this)
        e.preventDefault()
      })

      // input brands
      $(document).on("change", 'input[name="brand"]', function() {
        self.toggleAllBrands(self, this)
      })

      // price filter
      $(document).on("change submit", 'input[name="price"]', function() {
        self.setPrice(self, this)
      })

      $(document).on("change", ".js-show-count", function() {
        self.syncShowCount(this)
      })

      $(document).on("click", ".js-catalog-pagination li", function() {
        self.reloadTemplate(self, this)
      })

      $(document).on("click", ".js-reset-filter", function() {
        $("#filterForm").trigger("reset")
        self.reloadTemplate(self, this)
      })

      $(document).on("click", ".js-layoutview svg", function() {
        console.log($(this).index())
        self._option.layoutView = $(this).index() === 0 ? "grid" : "list"
      })

      // add active class to parent category
      // $(document).on('click', 'input[name="subCat', function() {
      //     e.preventDefault()
      // })
    },

    onloadTemplate: function() {
      this.renderTemplate({
        // url: `../public/data/product-catalog.json`,
        url: $(this._option.target).data("products"),
        target: "#js-product-item-template",
        container: ".js-product-items-container",
        wrapper: ".js-product-items-wrapper",
        callback: function(data) {
          const defaultColorPicker = Object.create(B2C.colorPicker)
          const defaultPagination = Object.create(B2C.pagination)
          const defaultPopover = Object.create(B2C.popover)
          const defaultTextExpand = Object.create(B2C.textExpand)
          const defaultScroll = Object.create(B2C.customScroll)

          // reinitialize colorPicker
          defaultColorPicker.init()
          defaultPopover.init()
          defaultTextExpand.init()
          defaultScroll.init()
          // re initialize pagination
          // get items per page
          let itemsPerPage = $(".js-show-count").val(),
            // get total items
            itemsTotal = data.totalItems

          defaultPagination.init({
            visiblePagination: 5,
            element: ".js-catalog-pagination",
            enableJumpTo: false,
            itemsTotal: itemsTotal,
            itemsPerPage: itemsPerPage,
            gotoLastText: "",
            gotoFirstText: "",
            gotoPrevText:
              '<img src="https://prep-community.musictribe.com/html/assets/pagination_arrow-prev.png" />',
            gotoNextText:
              '<img src="https://prep-community.musictribe.com/html/assets/pagination_arrow-next.png" />'
          })
        }
      })

      this.renderTemplate({
        url: $(this._option.target).data("filter"),
        target: "#js-product-filter",
        container: ".js-filter-container",
        wrapper: ".js-filter-wrapper",
        callback: function() {}
      })
    },

    reloadTemplate: function(self, element) {
      let filterData = $("#filterForm")
        .find("*[name!=price][name!=showCount]") //try using filter
        .serializeArray()
        .filter(item => item.value !== "")

      // get extra filter data
      for (let i = 0; i < self.getExtraFilter().length; i++) {
        filterData.push({
          name: self.getExtraFilter()[i].name,
          value: self.getExtraFilter()[i].value
        })
      }

      self.renderTemplate({
        url: $(this._option.target).data("products"),
        target: "#js-product-item-template",
        container: ".js-product-items-container",
        wrapper: ".js-product-items-wrapper",
        data: {
          filter: filterData
        },
        extraData: {
          layoutView: self._option.layoutView
        },
        callback: function(data) {
          const defaultColorPicker = Object.create(B2C.colorPicker)
          const defaultPopover = Object.create(B2C.popover)
          const defaultTextExpand = Object.create(B2C.textExpand)
          const defaultScroll = Object.create(B2C.customScroll)
          // reinitialize colorPicker
          defaultColorPicker.init()
          defaultPopover.init()
          defaultTextExpand.init()
          defaultScroll.init()

          if (!$(element).parents(".js-catalog-pagination")[0]) {
            const defaultPagination = Object.create(B2C.pagination)
            // re initialize pagination
            // get items per page
            let itemsPerPage = $(".js-show-count").val(),
              // get total items
              itemsTotal = data.totalItems

            defaultPagination.init({
              visiblePagination: 5,
              element: ".js-catalog-pagination",
              enableJumpTo: false,
              itemsTotal: itemsTotal,
              itemsPerPage: itemsPerPage,
              gotoPrevText:
                '<img src="https://prep-community.musictribe.com/html/assets/pagination_arrow-prev.png" />',
              gotoNextText:
                '<img src="https://prep-community.musictribe.com/html/assets/pagination_arrow-next.png" />'
            })
          }
        }
      })

      self.scrollTop()
    },

    renderTemplate: async function(args) {
      let handlebarTemplate = Object.create(B2C.handlebar),
        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) {
            console.log(data)
            resolve(data)
          }
        })
      })
    },

    toggleAllBrands: function(self, element) {
      // if element has all value check all checkbox of brands
      // else if all checked and unchecked one unchecked the all checkbox
      let value = $(element).val()

      if (value === "All") {
        $('input[name="brand"]').prop("checked", true)
      } else {
        $('input[name="brand"][value="All"]').prop("checked", false)
      }
    },

    setPrice: function(self, element) {
      let price = []

      $(".js-filter-price:checked").each(function() {
        price.push({
          min: $(this).attr("min"),
          max: $(this).attr("max")
        })
      })

      $("#price-min").val(price[0].min)
      $("#price-max").val(price[price.length - 1].max)
    },

    syncShowCount: function(element) {
      let value = $(element).val()
      $(".js-show-count").each(function() {
        $(this).val(value)
      })
    },

    getExtraFilter: function() {
      let filterData = new Array()

      filterData.push(
        {
          name: "itemsPerPage",
          value: $(".js-show-count").val()
        },
        {
          name: "pageNumber",
          value: $(".js-catalog-pagination")
            .find(".is-active")
            .data("pagination")
        }
      )

      return filterData
    },

    scrollTop: function() {
      window.scroll({
        top: 0,
        behavior: "smooth"
      })
    }
  }

  const defaultCatalogFilter = Object.create(B2C.catalogFilter)
  defaultCatalogFilter.init()
})(jQuery)
