import { formatUrlParams } from './format-url-params.mjs';
import { resolveUrlParams } from './resolve-url-params.mjs';
import '@babel/runtime/helpers/slicedToArray';

/**
 * 除保留参数外，一律移除
 * @param {string} url 地址
 * @param {string} removeKeyArr 待保留的参数名集合
 * @returns 重新拼接的地址
 * @example
 * // 地址是 hash 模式参数
 * keepUrlParams('http://www.test.com/#/detail?a=1&b=2&c=3', ['a', 'b']);
 * // => 'http://www.test.com/#/detail?a=1&b=2'
 * @example
 * // 地址 history 模式参数并存
 * keepUrlParams('http://www.test.com?a=1&b=2&c=3', ['a', 'b']);
 * // => 'http://www.test.com/?a=1&b=2'
 * @example
 * // 地址 history 模式参数并存 + 强制 history 模式返回
 * keepUrlParams('http://www.test.com?a=1&b=2&c=3', ['a', 'b'], true);
 * // => 'http://www.test.com/?a=1&b=2'
 * @example
 * // hash 模式和 history 模式参数并存
 * keepUrlParams('http://www.test.com?a=1&b=2&c=3#/detail?d=4', ['a', 'd']);
 * // => 'http://www.test.com/#/detail?a=1&d=4'
 * @example
 * // 地址是 hash 模式和 history 模式参数并存，且是多个参数
 * keepUrlParams('http://www.test.com?d=4&f=6#/detail?a=1&b=2&c=3', ['a', 'd']);
 * // => 'http://www.test.com/#/detail?d=4&a=1'
 */
function keepUrlParams() {
  var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  var keepKeyArr = arguments.length > 1 ? arguments[1] : undefined;
  var forceHistoryMode = arguments.length > 2 ? arguments[2] : undefined;
  // 获取链接上的所有参数
  var urlParamsObj = resolveUrlParams(url);
  // 只保留指定的key集合
  var keepParamsObj = {};
  Object.keys(urlParamsObj).forEach(function (key) {
    if (keepKeyArr.includes(key)) {
      keepParamsObj[key] = urlParamsObj[key];
    }
  });
  // 根据移除后的参数集合，重新拼接地址
  return formatUrlParams(url, keepParamsObj, forceHistoryMode);
}

export { keepUrlParams };
