Source: helpers/utils/filter-result-utils.js

/**
 * Utils module of filter result
 * @module Utils/FilterResultUtils
 */

import jQ from "jquery";
import Settings from "../settings";
import Utils from "../utils";
import Labels from "../labels";
import Globals from "../globals";
import SearchResultPanels from "../../components/filter/filter-result/filter-result-element/search-result-panels";
import SearchResultPanelItem from "../../components/filter/filter-result/filter-result-element/search-result-panel-item";

/**
 * Get the sorting list
 */
const getSortingList = () => {
	// Get all Sorting values
	// Deprecated
	var sortingValueArr = Settings.getSettingValue('general.sortingList');
	
	// New: Update Sorting in the Setting page
	var customSortingList = Settings.getSettingValue('general.customSortingList');
	if (customSortingList != '') {
		var sortingValueArr = customSortingList.trim().split('|');
		for (var i = sortingValueArr.length - 1; i >= 0; i--){
			if (sortingValueArr[i] == ''){
			sortingValueArr.splice(i, 1);
			}
		}
	}
  
	// Add extra Sorting
	var extraSortingValueArr = Settings.getSettingValue('general.extraSortingList');
	if (extraSortingValueArr) sortingValueArr = sortingValueArr.concat(extraSortingValueArr.split('|'));

	/**
	 * If it is not the search page, remove the 'relevance' option. 
	 * If it is the searach page, remove the 'manual' option
	 */
	if (!Utils.isSearchPage()) {
	  	var relevanceIndex = Utils.findIndexArray('relevance', sortingValueArr);
	  	if (relevanceIndex >= 0) sortingValueArr.splice(relevanceIndex, 1);
	} else{
	  	var manualSearchIndex = Utils.findIndexArray('manual', sortingValueArr);
	  	if (manualSearchIndex >= 0) sortingValueArr.splice(manualSearchIndex, 1);
	}

	// Build Labels
	var result = {};
	for (var k = 0; k < sortingValueArr.length; k++) {
		var sortingLabel = Labels.sortingList[sortingValueArr[k]];
		if (extraSortingValueArr.length > 0 && extraSortingValueArr.indexOf(sortingValueArr[k]) > -1) {
			var key = sortingValueArr[k].replace(/-/g, '_');
			sortingLabel = Labels[key];
		}
		result[sortingValueArr[k]] = sortingLabel;
	}
	return result;
};

/**
 * Return whether or not the pagination is advanced type
 */
const isAdvancedPaginationType = () => {
	return Settings.getSettingValue('general.paginationTypeAdvanced');
}

/**
 * Build URL for the product item
 * @param {Object} data The product data
 * @param {String} data.handle - The product handle
 * @param {Boolean} [hasCollection=true] - Set true if has collection in filter param
 */
const buildProductItemUrl = (data, hasCollection) => {
	// Get url information
	var params = Utils.getWindowLocation().search.substring(1);
	var pathname = window.location.pathname;
	var elements = pathname.split('/');
	// Get product handle
	var handle = typeof data === 'object' && data.hasOwnProperty('handle') ? data.handle : data;
	var hasCollection = typeof hasCollection !== 'undefined' ? hasCollection : Settings.getSettingValue('general.addCollectionToProductUrl');
	if (hasCollection) {
		// Homepage or Search page
		if (pathname == '/' || Utils.isSearchPage() || Utils.isVendorPage() || Utils.isTypePage()) {
			var preHandle = elements.indexOf(boostPFSAppConfig.general.current_locale) > -1 ? '/' + boostPFSAppConfig.general.current_locale + '/collections/all/products/' : '/collections/all/products/';
			return preHandle + handle;
		}
		// Tag Page
		else if (Utils.isTagPage()) {
			var preHandle = elements.indexOf(boostPFSAppConfig.general.current_locale) > -1 ? '/' + boostPFSAppConfig.general.current_locale + '/collections/' : '/collections/';
			var collectionHandleIndex = elements.indexOf("collections") + 1
			if (elements.length >= 4) return preHandle + elements[collectionHandleIndex] + '/products/' + handle;
			return '/collections/all/products/' + handle;
		} else {
			// Google cache URL
			// An URL of Google cache will look like this: webcache.googleusercontent.com/search?q=cache:xxx:https://xxx.xxx/collections/xxx+&....
			if (params.indexOf('cache:') > -1) {
				var collectionHandle = 'all';
				var temp = params.split('&')[0].split('?')[0].split('collections/');
				if (temp.length > 1) {
					if (temp[1].indexOf('/') > -1) {
						collectionHandle = temp[1].split('/')[0];
					}
					else {
						collectionHandle = temp[1];
					}
				}
				collectionHandle = collectionHandle.replace(/[`~!@#$%^&*()_|+\=?;:'",.<>\{\}\[\]\\\/]/g, '');
                return '/collections/' + collectionHandle + '/products/' + handle;
			}
          	var collectionHandleIndex = elements.indexOf("collections") + 1
			var preHandle = elements.indexOf(boostPFSAppConfig.general.current_locale) > -1 ? '/' + boostPFSAppConfig.general.current_locale + '/collections/' : '/collections/';
			if (typeof elements[2] !== 'undefined') {
				return preHandle + elements[collectionHandleIndex] + '/products/' + handle;
			}
			return window.location.pathname + '/products/' + handle;
		}
	}
	return elements.indexOf(boostPFSAppConfig.general.current_locale) > -1 ? '/' + boostPFSAppConfig.general.current_locale + '/products/' + handle : '/products/' + handle;
};

/**
 * Remove page param from URL
 * @param {String} link The link that needs to remove page param
 */
const removePageParamFromUrl = (link) => {
	if (Globals.queryParams.hasOwnProperty('page')) {
			link = link.replace('&page=' + Globals.queryParams.page, '').replace('?page=' + Globals.queryParams.page + '&', '?').replace('?page=' + Globals.queryParams.page, '');
	}
	return link;
}

/**
 * Remove collection_scope param from url
 * @param {String} link The link that needs to remove collection_scope
 */
const removeCollectionScopeParamFromUrl = (link) => {
	if (Globals.queryParams.hasOwnProperty('collection_scope')) {
			link = link.replace('&collection_scope=' + Globals.queryParams.collection_scope, '');
	}
	return link;
}


/**
 * Build link for other sections like: pagination, limit, sort, display
 * @param {String} type page, limit, sort or display
 * @param {(String|Nummer)} oldValue the currently param
 * @param {(String|Number)} newValue the new param
 */
const buildToolbarLink = (type, oldValue, newValue) => {
	var link = Utils.getWindowLocation().href;
	var oldParam = type + '=' + oldValue;
	var newParam = type + '=' + newValue;
	if (link.indexOf('?' + type + '=') > -1) {
		link = link.replace('?' + oldParam, '?' + newParam);
	} else {
		// Check the param whether exists in url
		// If Yes, replace old param with new param
		if (!SearchResultPanels.isPanelActive(SearchResultPanelItem.Enum.PRODUCT) && type == 'page' && link.indexOf('&' + type + '=') > -1) {
			var value = link.split('&page=')[1];
			if (value.indexOf('&') > -1) value = value.split('&')[0];
			link = link.replace('&page=' + value, '');
	  	}
		if (link.indexOf('&' + type + '=') > -1) {
			link = link.replace('&' + oldParam, '&' + newParam);
		}
		// If No, append new param to url
		else {
			if (Utils.getWindowLocation().search.length === 0) {
				link += '?' + newParam;
			} else {
				link = link.replace('?', '?' + newParam + '&');
			}
		}
	}
	
	// Remove page param if page = 1
	if (type == 'page' && newValue == 1) {
		link = link.replace('?page=1&', '?').replace('?page=1', '');
	}
	
	// Remove page param if firing an event which is different with the page event
	var additionalParams = ['display', 'sort', 'page', 'limit'];
	if (Globals.queryParams.hasOwnProperty('page') && additionalParams.indexOf(type) == -1) {
		var paginationParam = '&page=' + Globals.queryParams.page;
		link = link.replace(paginationParam, '');
	}
	return link;
};

/**
 * Return whether or not the pagination of a Product list page (Collection page, Type page, Search page, Tags page, ect) is default
 */
const isDefaultPaginationType = () => {
	return Settings.getSettingValue('general.paginationType') == 'default';
};

/**
 * Return whether or not the pagination of a Product list page (Collection page, Type page, Search page, Tags page, ect) is load more
 */
const isLoadMorePaginationType = () => {
	return Settings.getSettingValue('general.paginationType') == 'load_more';
}

/**
 * Return whether or not the pagination of a Product list page (Collection page, Type page, Search page, Tags page, ect) is infinite loading
 */
const isInfiniteLoadingPaginationType = () => {
	return Settings.getSettingValue('general.paginationType') == 'infinite';
};

/**
 * Return whether or not the loading previout page is enabled
 */
const isLoadPreviousPagePaginationType = () => {
	return (isLoadMorePaginationType() || isInfiniteLoadingPaginationType()) && isAdvancedPaginationType() && Settings.getSettingValue('general.activeLoadPreviousPage')
}

const getProductMetafield = (productData, namespace, key) => {
    if (productData.hasOwnProperty('metafields')) {
        var metafieldValue = productData['metafields'].filter(function(e) { return e.namespace == namespace && e.key == key; });
        if (typeof metafieldValue[0] !== 'undefined') {
            return metafieldValue[0]['value'];
        }
    }
    return null;
};

/**
 * Return TRUE if the filter not found any product item
 */
const isNoFilterResult = (totalProduct, eventType) => {
	return totalProduct <= 0 
		&& !(
			eventType === 'init' 
			&& Settings.getSettingValue('general.productAndVariantAvailable')
			&& Settings.getSettingValue('general.availableAfterFiltering')
		);
}

const FilterResultUtils = {
	getSortingList: getSortingList,
	getProductMetafield: getProductMetafield,
	isAdvancedPaginationType: isAdvancedPaginationType,
	buildProductItemUrl: buildProductItemUrl,
	removePageParamFromUrl: removePageParamFromUrl,
	removeCollectionScopeParamFromUrl: removeCollectionScopeParamFromUrl,
	buildToolbarLink: buildToolbarLink,
	isDefaultPaginationType: isDefaultPaginationType,
	isLoadMorePaginationType: isLoadMorePaginationType,
	isInfiniteLoadingPaginationType: isInfiniteLoadingPaginationType,
	isLoadPreviousPagePaginationType: isLoadPreviousPagePaginationType,
	isNoFilterResult: isNoFilterResult
}

export default FilterResultUtils;