/* Copyright © 2020 Splunk Inc.
SPLUNK CONFIDENTIAL – Use or disclosure of this material in whole or
in part without a valid written license from Splunk Inc. is PROHIBITED. */
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};

// src/utils/tagAPI.ts
var tagAPI_exports = {};
__export(tagAPI_exports, {
  createTags: () => createTags,
  deleteTags: () => deleteTags,
  fetchAllTags: () => fetchAllTags,
  fetchRESTURL: () => fetchRESTURL,
  fetchTags: () => fetchTags,
  flattenTagObject: () => flattenTagObject,
  getTagsHash: () => getTagsHash,
  handleResponse: () => handleResponse,
  updateTags: () => updateTags
});
module.exports = __toCommonJS(tagAPI_exports);

// esm-externals:@splunk/splunk-utils/fetch
var fetch_exports = {};
__export(fetch_exports, {
  default: () => fetch_default
});
var defaultImport = __toESM(require("@splunk/splunk-utils/fetch"));
__reExport(fetch_exports, require("@splunk/splunk-utils/fetch"));
var fetch_default = "default" in defaultImport ? defaultImport.default : defaultImport;

// esm-externals:@splunk/splunk-utils/config
var config_exports = {};
__export(config_exports, {
  default: () => config_default
});
var defaultImport2 = __toESM(require("@splunk/splunk-utils/config"));
__reExport(config_exports, require("@splunk/splunk-utils/config"));
var config_default = "default" in defaultImport2 ? defaultImport2.default : defaultImport2;

// esm-externals:@splunk/splunk-utils/url
var url_exports = {};
__export(url_exports, {
  default: () => url_default
});
var defaultImport3 = __toESM(require("@splunk/splunk-utils/url"));
__reExport(url_exports, require("@splunk/splunk-utils/url"));
var url_default = "default" in defaultImport3 ? defaultImport3.default : defaultImport3;

// src/utils/tagAPI.ts
var tagsURL = `/servicesNS/${encodeURIComponent(config_exports.username)}/${encodeURIComponent(config_exports.app)}/saved/fvtags`;
var getTagsHash = (tags) => {
  return tags.reduce((hash, tag) => {
    hash[`tag.${tag}`] = tag;
    return hash;
  }, {});
};
var handleResponse = (response, expectedStatus = 200) => __async(void 0, null, function* () {
  var _a;
  if (!(response == null ? void 0 : response.ok)) {
    const defaultErrorMsg = `${response == null ? void 0 : response.status} - ${response == null ? void 0 : response.statusText}`;
    const JSONErrorMsg = (0, fetch_exports.findErrorMessage)(yield response == null ? void 0 : response.json());
    const error = new Error((_a = JSONErrorMsg == null ? void 0 : JSONErrorMsg.text) != null ? _a : defaultErrorMsg);
    throw error;
  }
  if (response.status !== expectedStatus) {
    throw new Error(`Received status code ${response.status} instead of expected ${expectedStatus}`);
  }
  return response.json();
});
var fetchRESTURL = (..._0) => __async(void 0, [..._0], function* (url = "", namespace = {}, queryParams = {}, fetchParams = {}, responseCode = 200) {
  const queryParamsObj = new URLSearchParams(queryParams);
  const validQueryParams = JSON.stringify(queryParams) === "{}" ? "" : `?${queryParamsObj.toString()}`;
  const splunkURL = (0, url_exports.createRESTURL)(url, namespace);
  const fetchArgs = __spreadValues(__spreadValues({}, fetch_exports.defaultFetchInit), fetchParams);
  const response = yield fetch(`${splunkURL}${validQueryParams}`, fetchArgs);
  return handleResponse(response, responseCode);
});
var fetchTags = (fname = "", fvalue = "") => __async(void 0, null, function* () {
  const url = `${tagsURL}/${encodeURIComponent(fname)}%3D${encodeURIComponent(fvalue)}`;
  const result = yield fetchRESTURL(
    url,
    {
      app: config_exports.app,
      username: config_exports.username
    },
    {
      output_mode: "json"
    },
    { method: "GET" }
  );
  return result.entry[0].content.tags;
});
var fetchAllTags = () => __async(void 0, null, function* () {
  const url = tagsURL;
  const result = yield fetchRESTURL(
    url,
    {
      app: config_exports.app,
      username: config_exports.username
    },
    { output_mode: "json", count: 0 },
    { method: "GET" }
  );
  return result.entry.reduce((fvTagsMap, tagObject) => {
    if (!tagObject.content.disabled) {
      fvTagsMap[tagObject.name] = tagObject.content.tags;
    }
    return fvTagsMap;
  }, {});
});
var createTags = (..._0) => __async(void 0, [..._0], function* (fname = "", fvalue = "", tags = []) {
  const url = tagsURL;
  const data = __spreadValues({
    name: `${fname}=${fvalue}`,
    output_mode: "json"
  }, getTagsHash(tags));
  const dataObj = new URLSearchParams(data);
  const result = yield fetchRESTURL(
    url,
    {
      app: config_exports.app,
      username: config_exports.username
    },
    {},
    {
      method: "POST",
      body: dataObj.toString()
    },
    201
  );
  return result.entry[0].content.tags;
});
var updateTags = (..._0) => __async(void 0, [..._0], function* (fname = "", fvalue = "", tags = []) {
  const url = `${tagsURL}/${encodeURIComponent(fname)}%3D${encodeURIComponent(fvalue)}`;
  const data = __spreadValues({
    output_mode: "json"
  }, getTagsHash(tags));
  const dataObj = new URLSearchParams(data);
  const result = yield fetchRESTURL(
    url,
    {
      app: config_exports.app,
      username: config_exports.username
    },
    {},
    {
      method: "POST",
      body: dataObj.toString()
    }
  );
  return result.entry[0].content.tags;
});
var deleteTags = (fname = "", fvalue = "") => __async(void 0, null, function* () {
  const url = `${tagsURL}/${encodeURIComponent(fname)}%3D${encodeURIComponent(fvalue)}`;
  const result = yield fetchRESTURL(
    url,
    {
      app: config_exports.app,
      username: config_exports.username
    },
    { output_mode: "json" },
    { method: "DELETE" }
  );
  return result.entry;
});
var flattenTagObject = (tags) => {
  const flattenedTags = {};
  const fields = tags ? Object.keys(tags) : [];
  fields.forEach((field) => {
    const fieldValues = Object.keys(tags[field]);
    fieldValues.forEach((fieldValue) => {
      const tagsList = tags[field][fieldValue];
      flattenedTags[`${field}=${fieldValue}`] = tagsList;
    });
  });
  return flattenedTags;
};
//# sourceMappingURL=tagAPI.js.map
