/*
	Author: Kevin Saquing
	Filename: searchbox.js
	Description: Used in the autocomplete of Search box in header
	Dependencies: Jquery-UI
	How to use: 
*/

;(function($) {
  "use strict"

  NOP.searchBox = {
    init: function(option) {
      this.defaults = {
        target: "#jsSearchInput",
        resultsCon: "#jsSearchBoxResults",
        resultsConHeadText: "#jsSearchBoxHeadText",
        minLength: 3,
        routeUrl: "/catalog/searchtermautocomplete",
        delay: 500
      }

      this.constructor = $.extend({}, this.defaults, option)
      this.onSearch()
    },
    onSearch: function() {
      const self = this
      const _constructor = self.constructor

      let {
        target,
        delay,
        minLength,
        resultsCon,
        routeUrl,
        resultsConHeadText
      } = _constructor

      $(target)
        .autocomplete({
          delay: delay,
          minLength: minLength,
          source: routeUrl,
          search: function(event, data) {
            $(resultsCon).empty()
            $(resultsConHeadText).removeClass("d-none")
            $(resultsConHeadText).text("Searching...")
          },
          response: function(event, data) {
            console.log(data)
            if (data.content.length == 0) {
              $(resultsConHeadText).text("No result found")
            } else {
              $(resultsConHeadText).text("Recommended Results")
            }
          }
        })
        .data("ui-autocomplete")._renderItem = function(ul, item) {
        return $(self.getTemplate(item)).appendTo(resultsCon)
      }
    },
    getTemplate: function(data) {
      return `<a class="header__search-item" href="${data.producturl}">
			<p class="header__search-item-title">${data.label}</p>
			<p class="header__search-item-desc">1. I just recently punched my X32 Compact, 1st thing I notice comes with firmware 3.12 out of the box, however, the Behringer support page only shows 3.11. Why is this?2. Is there a firmware revion sheet to show the changes and update features on ... </p>
		</a>`
    }
  }

  // Prevents from overwriting
  Object.freeze(NOP.searchBox)
})(jQuery)
