(function($, Drupal) {

  const query_string = window.query_string;

  const viewsToCheck = ['newsroom_view','newsroom_view_1'];

  const getParent = (view_display_id) => {
    return `.view-display-id-${view_display_id}`;
  }

  const deduceView = () => {
    let returnValue;
    viewsToCheck.forEach(x => {
      if ($(getParent(x))) {
        returnValue = x;
      }
    })
    return returnValue;
  }

  const uppercaseFirstLetter = (string) => string.length ? string[0].toUpperCase() + string.slice(1) : string;

  const getUsableLabel = (i = '') => {

    var matches = i.match(/\[(.*?)\]/);
    var beginning = '';
    if ($.isArray(matches)) {
        const match_one = matches[1];
        if ($.inArray(match_one,['min']) !== -1) {
          beginning = 'start';
        }else if ($.inArray(match_one,['max','limit']) !== -1) {
          beginning = 'end';
        }
    }

    var end = getUsableParam(i);
    const complete = beginning + '_' + end;
    return complete.split('_').filter(x => x).map(string => string && string.length ? uppercaseFirstLetter(string) : string).join(' ');
  }

  const getUsableParam = (i = '') => {
    var end = i;
    const indexOfOpenBracket = i.indexOf("[");
    if (indexOfOpenBracket !== -1) {
      end = i.substring(0, indexOfOpenBracket);
    }
    return end;
  }
  const skippableParams = ['ALL'];
  const replaceAndCreateButtons = (view_display_id = deduceView(), extraData = {}, queryString = window.location.search) => {
    if (view_display_id && queryString) {
      const params = query_string.parse(queryString);
      const buttons = [];

      for (var param in params) {
          if (extraData[param] !== undefined) {
            delete params[param];
          }
      }

      const base = `${window.location.origin}${window.location.pathname}?`;

      for (var param in params) {
          if (!params[param] || $.inArray(params[param].toUpperCase(), skippableParams) !== -1) {
            continue;
          }
          const enumerated = params[param].split(',').filter(x => x);
          if (enumerated.length > 1) {
            enumerated.forEach((x,i) => {
              if (x) {
                const newParams = {...params};
                newParams[param] = newParams[param].replace(x,'').replace(',,','');
                const completeQueryString = `${base}${query_string.stringify(newParams)}`;
                const usableLable = getUsableLabel(param);
                const button = {
                  label: uppercaseFirstLetter(usableLable),
                  param: getUsableParam(param),
                  value: params[param].split('_').filter(x => x).map(string => string ? uppercaseFirstLetter(string) : string).join(' '),
                  href: completeQueryString
                };
                buttons.push(button);
              }
            })
          }else{
              const newParams = {...params};
              delete newParams[param];
              const completeQueryString = `${base}${query_string.stringify(newParams)}`;
              const usableLable = getUsableLabel(param);
              const button = {
                label: uppercaseFirstLetter(usableLable),
                param: getUsableParam(param),
                value: params[param].split('_').filter(x => x).map(string => string ? uppercaseFirstLetter(string) : string).join(' '),
                href: completeQueryString
              };
              buttons.push(button);
          }
      }

      const parent_class = 'disable_filter_buttons';
      const local_class = `views_filter_buttons-${view_display_id}`;
      const parent = $(getParent(view_display_id)).children('div.view-filters')[0];
      const selector = `div.${parent_class}.${local_class}`;
      let existing = $(selector);
      if (existing.length) {
        existing.empty();
      } else {
        const placeForButtons = `<div class="${parent_class} ${local_class}"></div>`;
        $(parent).after(placeForButtons);
      }
      existing = $(selector);
      if ($.isArray(buttons) && buttons.length) {
        const buttonsToPlace = buttons.map(x => {
          const {
            href,
            label,
            param,
            value
          } = x;
          // return `<div class="views_filter_buttons-button-container ${param}"><a class="views_filter_buttons-button ${param}" href="${href}"><span class="views_filter_buttons-button-label ${param}">${label}</span><div class="views_filter_buttons-button-divider ${param}"/><span class="views_filter_buttons-button-value ${param}">${value}</span><span class="views_filter_buttons-button-x">X</span></a></div>`;
          return `<div class="views_filter_buttons-button-container ${param}"><div class="views_filter_buttons-button ${param}"><span class="views_filter_buttons-button-label ${param}">${label}</span><div class="views_filter_buttons-button-divider ${param}"></div><span class="views_filter_buttons-button-value ${param}">${value}</span><a class="views_filter_buttons-button-x" href="${href}">X</a></div></div>`;
        }).join('');
        existing.append(buttonsToPlace);
      }
    }
  }

  // Process on initial get
  replaceAndCreateButtons(undefined, undefined, undefined);

  const processAJAXResponse = (event, xhr, settings) => {
    xhr.then(x => {
      if (settings.extraData && $.inArray(settings.extraData.view_name, viewsToCheck) !== -1) {
        replaceAndCreateButtons(settings.extraData.view_display_id, settings.extraData, settings.data);
      }
    })
  }

  $(document).ajaxSuccess(processAJAXResponse);

})(jQuery, Drupal);