window.addEventListener('load', function () {
  var checkedValue = null;
  var inputElements = document.getElementsByClassName('blog-filter-checkbox');

  // get all query parameters in the url
  let queryParameters = new URLSearchParams(window.location.search);

  // create an empty object to house query parameters
  let queryParamObject = {};

  // on load create an object with the queryparameters
  for (var value of queryParameters.keys()) {
    queryParamObject[value] = queryParameters.get(value);

    let paramArray = queryParameters.get(value).split(',');

    for (var i = 0; i < inputElements.length; i++) {
      if (paramArray.includes(inputElements[i].value)) {
        inputElements[i].checked = true;
      }
    }
  }

  // loop through checkboxes and listen for change event
  for (var i = 0; inputElements[i]; ++i) {
    inputElements[i].addEventListener('change', async function () {
      // set variable to reflect added query aprameters
      queryParameters = new URLSearchParams(window.location.search);

      // the data-key of the element
      checkedKey = this.getAttribute('data-category');

      // if a value gets checked, add to object and url
      if (this.checked) {
        // the value of the checkbox
        checkedValue = this.value;

        // if the key on the object exists, add the checked value
        if (queryParamObject[checkedKey] !== undefined) {
          if (queryParamObject[checkedKey]) {
            queryParamObject[checkedKey] = queryParameters.get(checkedKey) + ',' + checkedValue;
          }
        } else {
          /* else if no key exists, create one and add checked value */
          queryParameters.set(checkedKey, checkedValue);
          for (var value of queryParameters.keys()) {
            queryParamObject[value] = queryParameters.get(value);
          }
        }

        // create string from the query parameter object and construct the url parameters
        var filterQueryString = Object.keys(queryParamObject)
          .map(function (key) {
            return key + '=' + queryParamObject[key];
          })
          .join('&');

        // create the new path with the query parameters
        var newRelativePathQuery = window.location.pathname + '?' + filterQueryString;

        // push the history state into the address bar to reflect url parameters
        history.pushState(null, '', newRelativePathQuery);

        setTimeout(fetchBlogPosts(queryParamObject), 200);
      } else {
        checkedValue = this.value;
        /* else if a value gets unchecked, remove from object and url */

        // get query parameters based on checked key
        let queryArray = queryParameters.get(checkedKey).split(',');

        if (queryArray.length > 1) {
          const queryIndex = queryArray.indexOf(checkedValue);
          if (queryParamObject[checkedKey]) {
            queryArray.splice(queryIndex, 1);
            queryParamObject[checkedKey] = queryArray.toString();
          }
        } else {
          delete queryParamObject[checkedKey];
        }

        var filterQueryString = Object.keys(queryParamObject)
          .map(function (key) {
            return key + '=' + queryParamObject[key];
          })
          .join('&');

        var newRelativePathQuery = window.location.pathname + '?' + filterQueryString;

        history.pushState(null, '', newRelativePathQuery);

        setTimeout(fetchBlogPosts(queryParamObject), 200);
      }
    });
  }

  async function fetchBlogPosts(queryParamObject) {
    await jQuery.ajax({
      url: blog_object.ajax_url,
      type: 'get',
      data: {
        action: 'filter_blog',
        topic: queryParamObject['topic'],
        product: queryParamObject['product'],
        technology: queryParamObject['technology'],
        company: queryParamObject['company'],
        role: queryParamObject['role'],
        industry: queryParamObject['industry'],
        category: location.pathname.split('/')[2],
      },
      success: function (data) {
        jQuery('#datafetch').html(data);
      },
    });
  }

  function resetBlogFilters() {
    var resetButton = document.querySelector('#blog-reset-filters');
    var checkboxes = document.getElementsByClassName('blog-filter-checkbox');

    if (checkboxes.length) {
      resetButton.addEventListener('click', function () {
        for (var i = 0; checkboxes[i]; ++i) {
          if (checkboxes[i].checked != false) {
            checkboxes[i].click();
          }
        }
      });
    }
  }

  resetBlogFilters();
});
