/**
 * @file
 * Add apply button to the summary.
 */

(function ($, Drupal, drupalSettings) {

  'use strict';

  Drupal.facets = Drupal.facets || {};
  Drupal.behaviors.applyButton = {
    attach: function (context) {
      Drupal.facets.applyButton(context);
    }
  };

  /**
   * Add apply button to the summary.
   */
  Drupal.facets.applyButton = function (context) {
    var applyButton = $(once('facets-apply-button', '.facets-apply-button', context));

    if (applyButton.length > 0) {
      $(once('applyButton', applyButton)).bind('click', function (e) {
        // Build the url based on the selected checkboxes.
        var queryString = $.parseParams(window.location.href);
        var currentFacetValues = [];
        if (typeof queryString['f'] == 'object') {
          currentFacetValues = !$.isArray(queryString['f']) ? Object.values(queryString['f']) : queryString['f'];
        }

        var $checkboxWidgets = $('.js-facets-widget.item-list__checkbox');
        $checkboxWidgets.each(function (index, widget) {
          var $widget = $(widget);
          var $widgetLinks = $widget.find('.facet-item > a');
          var facetSettings = drupalSettings.facets[$widget.data('drupal-facet-id')];

          // If disable autosubmit configuration is set.
          if (facetSettings.disable_autosubmit) {
            $widgetLinks.each(function () {
              var $link = $(this);
              var value = $widget.data('drupal-facet-alias') + ':' + $link.data('drupal-facet-item-value');
              var setted_index = $.inArray(value, currentFacetValues);

              // Add the facet, if it is not already set.
              if ($link.siblings('.facets-checkbox').is(':checked') && setted_index === -1) {
                currentFacetValues.push(value);
              }
              // Remove the facet if set.
              else if ($link.siblings('.facets-checkbox').is(':checked') === false && setted_index !== -1) {
                currentFacetValues.splice(setted_index, 1);
              }
            });
          }
        });

        var $dropdownWidgets = $('.js-facets-dropdown-links.item-list__dropdown');
        $dropdownWidgets.each(function (index, widget) {
          var $widget = $(widget);
          var facetSettings = drupalSettings.facets['dropdown_widget'][$widget.data('drupal-facet-id')];

          // If disable autosubmit configuration is set.
          if (facetSettings.disable_autosubmit) {
            var $dropdownLinks = $widget.find('a');
            var selectedValue = $(widget).siblings("select").children(":selected").text().trim();

            $dropdownLinks.each(function() {
              var value = $widget.data('drupal-facet-alias') + ':' + $(this).data('drupal-facet-item-value');
              var setted_index = $.inArray(value, currentFacetValues);

              if (setted_index !== -1) {
                currentFacetValues.splice(setted_index, 1);
              }
              
              if ($(this).data('drupal-facet-item-value') == selectedValue) {
                currentFacetValues.push(value);
              }
            });
          }
        });

        if (currentFacetValues.length > 0) {
          queryString['f'] = $.extend({}, currentFacetValues);
        }
        else {
          queryString['f'] = null;
        }
        var path = window.location.pathname;
        var queryStringObj = $.extend({}, queryString);

        // Remove pager parameter as the current page could not exist with
        // the new facets.
        if (typeof queryStringObj.page !== 'undefined') {
          queryStringObj.page = null;
        }

        var href = path + '?' + $.param(queryStringObj);
        $checkboxWidgets.first().trigger('facets_filter', [ href ]);
        $("select.facets-dropdown").first().trigger('facets_filter', [ href ]);

        // We have to trigger attaching of behaviours, so that Facets JS API can
        // register handlers on checkbox widgets.
        Drupal.attachBehaviors(this.parentNode, Drupal.settings);
      });
    }
  };

})(jQuery, Drupal, drupalSettings);


// Add an URL parser to JQuery that returns an object
// This function is meant to be used with an URL like the window.location
// Use: $.parseParams('http://mysite.com/?var=string') or $.parseParams() to parse the window.location
// Simple variable:  ?var=abc                        returns {var: "abc"}
// Simple object:    ?var.length=2&var.scope=123     returns {var: {length: "2", scope: "123"}}
// Simple array:     ?var[]=0&var[]=9                returns {var: ["0", "9"]}
// Array with index: ?var[0]=0&var[1]=9              returns {var: ["0", "9"]}
// Nested objects:   ?my.var.is.here=5               returns {my: {var: {is: {here: "5"}}}}
// All together:     ?var=a&my.var[]=b&my.cookie=no  returns {var: "a", my: {var: ["b"], cookie: "no"}}
// You just cant have an object in an array, e.g. ?var[1].test=abc DOES NOT WORK
(function ($) {
  //
  var re = /([^&=]+)=?([^&]*)/g;
  var decode = function (str) {
    return decodeURIComponent(str.replace(/\+/g, ' '));
  };
  $.parseParams = function (query) {

    // recursive function to construct the result object
    function createElement(params, key, value) {
      key = key + '';

      // if the key is a property
      if (key.indexOf('.') !== -1) {
        // extract the first part with the name of the object
        var list = key.split('.');

        // the rest of the key
        var new_key = key.split(/\.(.+)?/)[1];

        // create the object if it doesnt exist
        if (!params[list[0]]) params[list[0]] = {};

        // if the key is not empty, create it in the object
        if (new_key !== '') {
          createElement(params[list[0]], new_key, value);
        } else console.warn('parseParams :: empty property in key "' + key + '"');
      } else
        // if the key is an array
      if (key.indexOf('[') !== -1) {
        // extract the array name
        var list = key.split('[');
        key = list[0];

        // extract the index of the array
        var list = list[1].split(']');
        var index = list[0]

        // if index is empty, just push the value at the end of the array
        if (index == '') {
          if (!params) params = {};
          if (!params[key] || !$.isArray(params[key])) params[key] = [];
          params[key].push(value);
        } else
          // add the value at the index (must be an integer)
        {
          if (!params) params = {};
          if (!params[key] || !(typeof params[key] == 'object')) params[key] = {};
          params[key][parseInt(index)] = value;
        }
      } else
        // just normal key
      {
        if (!params) params = {};
        params[key] = value;
      }
    }

    // be sure the query is a string
    query = query + '';

    if (query === '') query = window.location + '';

    var params = {}, e;
    if (query) {
      // remove # from end of query
      if (query.indexOf('#') !== -1) {
        query = query.substr(0, query.indexOf('#'));
      }

      // remove ? at the begining of the query
      if (query.indexOf('?') !== -1) {
        query = query.substr(query.indexOf('?') + 1, query.length);
      } else return {};

      // empty parameters
      if (query == '') return {};

      // execute a createElement on every key and value
      while (e = re.exec(query)) {
        var key = decode(e[1]);
        var value = decode(e[2]);
        createElement(params, key, value);
      }
    }
    return params;
  };
})(jQuery);