/* 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/components/EditTagsModal/index.tsx
var EditTagsModal_exports = {};
__export(EditTagsModal_exports, {
  default: () => EditTagsModal_default,
  formatTagsToArray: () => formatTagsToArray
});
module.exports = __toCommonJS(EditTagsModal_exports);

// esm-externals:react
var react_exports = {};
__export(react_exports, {
  default: () => react_default
});
var defaultImport = __toESM(require("react"));
__reExport(react_exports, require("react"));
var react_default = "default" in defaultImport ? defaultImport.default : defaultImport;

// esm-externals:@splunk/react-ui/Button
var Button_exports = {};
__export(Button_exports, {
  default: () => Button_default
});
var defaultImport2 = __toESM(require("@splunk/react-ui/Button"));
__reExport(Button_exports, require("@splunk/react-ui/Button"));
var Button_default = "default" in defaultImport2 ? defaultImport2.default : defaultImport2;

// esm-externals:@splunk/react-ui/ControlGroup
var ControlGroup_exports = {};
__export(ControlGroup_exports, {
  default: () => ControlGroup_default
});
var defaultImport3 = __toESM(require("@splunk/react-ui/ControlGroup"));
__reExport(ControlGroup_exports, require("@splunk/react-ui/ControlGroup"));
var ControlGroup_default = "default" in defaultImport3 ? defaultImport3.default : defaultImport3;

// esm-externals:@splunk/react-ui/Modal
var Modal_exports = {};
__export(Modal_exports, {
  default: () => Modal_default
});
var defaultImport4 = __toESM(require("@splunk/react-ui/Modal"));
__reExport(Modal_exports, require("@splunk/react-ui/Modal"));
var Modal_default = "default" in defaultImport4 ? defaultImport4.default : defaultImport4;

// esm-externals:@splunk/react-ui/TextArea
var TextArea_exports = {};
__export(TextArea_exports, {
  default: () => TextArea_default
});
var defaultImport5 = __toESM(require("@splunk/react-ui/TextArea"));
__reExport(TextArea_exports, require("@splunk/react-ui/TextArea"));
var TextArea_default = "default" in defaultImport5 ? defaultImport5.default : defaultImport5;

// esm-externals:@splunk/react-ui/ComboBox
var ComboBox_exports = {};
__export(ComboBox_exports, {
  default: () => ComboBox_default
});
var defaultImport6 = __toESM(require("@splunk/react-ui/ComboBox"));
__reExport(ComboBox_exports, require("@splunk/react-ui/ComboBox"));
var ComboBox_default = "default" in defaultImport6 ? defaultImport6.default : defaultImport6;

// esm-externals:@splunk/react-ui/Message
var Message_exports = {};
__export(Message_exports, {
  default: () => Message_default
});
var defaultImport7 = __toESM(require("@splunk/react-ui/Message"));
__reExport(Message_exports, require("@splunk/react-ui/Message"));
var Message_default = "default" in defaultImport7 ? defaultImport7.default : defaultImport7;

// esm-externals:@splunk/ui-utils/i18n
var i18n_exports = {};
__export(i18n_exports, {
  default: () => i18n_default
});
var defaultImport8 = __toESM(require("@splunk/ui-utils/i18n"));
__reExport(i18n_exports, require("@splunk/ui-utils/i18n"));
var i18n_default = "default" in defaultImport8 ? defaultImport8.default : defaultImport8;

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

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

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

// 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;
});

// src/components/EditTagsModal/index.tsx
var formatTagsToArray = (tagsString) => {
  return tagsString ? tagsString.trim().replace(/,/g, " ").split(/\s+/) : [];
};
var EditTagsModal = (props) => {
  var _a;
  const { fieldName, fieldValue, tags, isOpen, updateIsModalOpen, updateAllTags } = props;
  const formattedTags = (_a = tags == null ? void 0 : tags.join(", ")) != null ? _a : "";
  const [tagsString, setTagsString] = (0, react_exports.useState)(formattedTags);
  const [errorMessage, setErrorMessage] = (0, react_exports.useState)("");
  const [isNew, setIsNew] = (0, react_exports.useState)(!tags);
  const handleRequestClose = () => {
    updateIsModalOpen(false);
  };
  const handleSave = () => __async(void 0, null, function* () {
    setErrorMessage("");
    const tagArray = formatTagsToArray(tagsString);
    try {
      if (isNew) {
        yield createTags(fieldName, fieldValue, tagArray);
      } else if (tagArray.length === 0) {
        yield deleteTags(fieldName, fieldValue);
      } else {
        yield updateTags(fieldName, fieldValue, tagArray);
      }
      handleRequestClose();
      const allTags = yield fetchAllTags();
      updateAllTags(allTags);
    } catch (e) {
      setErrorMessage(e.message);
    }
  });
  const onChange = (e) => {
    const tagString = e.target.value;
    setTagsString(tagString);
  };
  const TEXT = {
    TITLE: (0, i18n_exports._)("Create tags"),
    FIELD_LABEL: (0, i18n_exports._)("Field value"),
    TAGS_LABEL: (0, i18n_exports._)("Tag(s)"),
    HELP: (0, i18n_exports._)("Comma or space separated list of tags."),
    CANCEL: (0, i18n_exports._)("Cancel"),
    SAVE: (0, i18n_exports._)("Save"),
    FIELD_PLACEHOLDER: `${fieldName}=${fieldValue}`
  };
  (0, react_exports.useEffect)(() => {
    const resetModal = () => {
      setErrorMessage("");
      setTagsString(formattedTags);
    };
    const checkTagsExist = () => __async(void 0, null, function* () {
      var _a2;
      try {
        const tagsIncludingDisabled = yield fetchTags(fieldName, fieldValue);
        setTagsString((_a2 = tagsIncludingDisabled == null ? void 0 : tagsIncludingDisabled.join(", ")) != null ? _a2 : "");
        setIsNew(false);
      } catch (e) {
        setIsNew(true);
      }
    });
    if (isOpen) {
      resetModal();
      checkTagsExist();
    }
  }, [isOpen, fieldName, fieldValue, formattedTags]);
  return /* @__PURE__ */ react_default.createElement(
    Modal_default,
    {
      "data-test": "edit-tags-modal",
      onRequestClose: handleRequestClose,
      open: isOpen,
      style: { width: "550px" },
      onClick: (syntheticEvent) => {
        syntheticEvent.stopPropagation();
      },
      onMouseDown: (syntheticEvent) => {
        syntheticEvent.stopPropagation();
      },
      onMouseUp: (syntheticEvent) => {
        syntheticEvent.stopPropagation();
      },
      returnFocus: () => {
      }
    },
    /* @__PURE__ */ react_default.createElement(Modal_default.Header, { title: TEXT.TITLE }),
    /* @__PURE__ */ react_default.createElement(Modal_default.Body, null, errorMessage && /* @__PURE__ */ react_default.createElement(Message_default, { type: "error" }, errorMessage), /* @__PURE__ */ react_default.createElement(ControlGroup_default, { label: TEXT.FIELD_LABEL }, /* @__PURE__ */ react_default.createElement(
      ComboBox_default,
      {
        "data-test": "edit-tags-modal-field",
        disabled: true,
        placeholder: TEXT.FIELD_PLACEHOLDER
      }
    )), /* @__PURE__ */ react_default.createElement(ControlGroup_default, { label: TEXT.TAGS_LABEL, help: TEXT.HELP }, /* @__PURE__ */ react_default.createElement(TextArea_default, { "data-test": "edit-tags-modal-textarea", value: tagsString, onChange }))),
    /* @__PURE__ */ react_default.createElement(Modal_default.Footer, null, /* @__PURE__ */ react_default.createElement(Button_default, { appearance: "secondary", onClick: handleRequestClose, label: TEXT.CANCEL }), /* @__PURE__ */ react_default.createElement(Button_default, { appearance: "primary", onClick: handleSave, label: TEXT.SAVE }))
  );
};
var EditTagsModal_default = EditTagsModal;
//# sourceMappingURL=index.js.map
