"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.convertToShortUrl = convertToShortUrl;
exports.createExploratoryViewUrl = createExploratoryViewUrl;
exports.encodeUriIfNeeded = encodeUriIfNeeded;
var _rison = _interopRequireDefault(require("@kbn/rison"));
var _url_constants = require("./constants/url_constants");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

function convertToShortUrl(series) {
  const {
    operationType,
    seriesType,
    breakdown,
    filters,
    reportDefinitions,
    dataType,
    selectedMetricField,
    hidden,
    name,
    color,
    ...restSeries
  } = series;
  return {
    [_url_constants.URL_KEYS.OPERATION_TYPE]: operationType,
    [_url_constants.URL_KEYS.SERIES_TYPE]: seriesType,
    [_url_constants.URL_KEYS.BREAK_DOWN]: breakdown,
    [_url_constants.URL_KEYS.FILTERS]: filters,
    [_url_constants.URL_KEYS.REPORT_DEFINITIONS]: reportDefinitions,
    [_url_constants.URL_KEYS.DATA_TYPE]: dataType,
    [_url_constants.URL_KEYS.SELECTED_METRIC]: selectedMetricField,
    [_url_constants.URL_KEYS.HIDDEN]: hidden,
    [_url_constants.URL_KEYS.NAME]: name,
    [_url_constants.URL_KEYS.COLOR]: color ? escape(color) : undefined,
    ...restSeries
  };
}
function createExploratoryViewUrl({
  reportType,
  allSeries
}, baseHref = '') {
  const allShortSeries = allSeries.map(series => convertToShortUrl(series));
  return baseHref + `/app/exploratory-view/#?reportType=${reportType}&sr=${encodeUriIfNeeded(_rison.default.encode(allShortSeries))}`;
}

/**
 * Encodes the uri if it contains characters (`/?@&=+#`).
 * It doesn't consider `,` and `:` as they are part of [Rison]{@link https://www.npmjs.com/package/rison-node} syntax.
 *
 * @param uri Non encoded URI
 */
function encodeUriIfNeeded(uri) {
  if (!uri) {
    return uri;
  }
  if (/[\/?@&=+#]/.test(uri)) {
    return encodeURIComponent(uri);
  }
  return uri;
}