/* 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 __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
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 __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
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/LocalIconProvider.js
var LocalIconProvider_exports = {};
__export(LocalIconProvider_exports, {
  KEY: () => KEY,
  b64EncodeUnicode: () => b64EncodeUnicode,
  default: () => LocalIconProvider_default
});
module.exports = __toCommonJS(LocalIconProvider_exports);

// esm-externals:uuid-v4
var uuid_v4_exports = {};
__export(uuid_v4_exports, {
  default: () => uuid_v4_default
});
var defaultImport = __toESM(require("uuid-v4"));
__reExport(uuid_v4_exports, require("uuid-v4"));
var uuid_v4_default = "default" in defaultImport ? defaultImport.default : defaultImport;

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

// esm-externals:@splunk/visualization-context/Provider
var Provider_exports = {};
__export(Provider_exports, {
  default: () => Provider_default
});
var defaultImport3 = __toESM(require("@splunk/visualization-context/Provider"));
__reExport(Provider_exports, require("@splunk/visualization-context/Provider"));
var Provider_default = "default" in defaultImport3 ? defaultImport3.default : defaultImport3;

// src/LocalIconProvider.js
var b64EncodeUnicode = (str) => (
  // first we use encodeURIComponent to get percent-encoded UTF-8,
  // then we convert the percent encodings into raw bytes which
  // can be fed into btoa.
  btoa(
    encodeURIComponent(str).replace(
      /%([0-9A-F]{2})/g,
      (match, p1) => String.fromCharCode(parseInt(`0x${p1}`, 16))
    )
  )
);
var KEY = "__icons__";
var LocalIconProvider = class extends Provider_default {
  constructor() {
    super();
  }
  /**
   * return provider type
   * @return {String} 'local'
   */
  getType() {
    return "local";
  }
  /**
   * upload one new icon
   */
  upload(dataURI, metaData) {
    return __async(this, null, function* () {
      const response = yield fetch(dataURI);
      const text = yield response.text();
      const parser = new DOMParser();
      const xmlDoc = parser.parseFromString(text, "text/xml");
      const svg = xmlDoc.getElementsByTagName("svg")[0];
      if (!svg.getAttribute("viewBox")) {
        throw new Error((0, i18n_exports._)("Please upload a valid svg with viewBox attribute."));
      }
      svg.setAttribute("preserveAspectRatio", "none");
      const serializer = new XMLSerializer();
      const svgStr = b64EncodeUnicode(serializer.serializeToString(svg));
      const iconDataURI = `data:image/svg+xml;base64,${svgStr}`;
      try {
        const icon = { dataURI: iconDataURI, metaData };
        const id = uuid_v4_default();
        let icons = JSON.parse(localStorage.getItem(KEY) || "{}");
        icons = __spreadProps(__spreadValues({}, icons), { [id]: icon });
        localStorage.setItem(KEY, JSON.stringify(icons));
        return id;
      } catch (error) {
        throw new Error(
          (0, i18n_exports._)("The icon cannot be uploaded. Please check whether your localStorage is full.")
        );
      }
    });
  }
  /**
   * get one icon by icon id
   */
  getById(id) {
    const icons = JSON.parse(localStorage.getItem(KEY) || "{}");
    if (icons[id]) {
      return icons[id];
    }
    throw new Error((0, i18n_exports._)("The icon is not found."));
  }
  /**
   * get all icon ids
   * @params options
   * @params options.meta   a list of meta data attribute that would be returned with each id
   * @params options.search  a search string to filter the returned icons
   */
  listIds({ offset = 0, count = 100, meta = [], search = null }) {
    try {
      const icons = JSON.parse(localStorage.getItem(KEY) || "{}");
      const results = [];
      Object.keys(icons).slice(offset, count).forEach((id) => {
        const icon = { id };
        const iconMeta = icons[id].metaData || {};
        const isSearchedIcon = search != null && Object.keys(iconMeta).some((attr) => {
          const iconMetaValue = iconMeta[attr].toLowerCase();
          return iconMetaValue.indexOf(search.toLowerCase()) > -1;
        });
        if (search == null || isSearchedIcon) {
          if (meta && meta.length) {
            icon.metaData = {};
            meta.forEach((attr) => {
              if (iconMeta[attr] != null) {
                icon.metaData[attr] = iconMeta[attr];
              }
            });
          }
          results.push(icon);
        }
      });
      return results;
    } catch (error) {
      throw new Error((0, i18n_exports._)("The icon ids cannot be listed."));
    }
  }
  /**
   * delete an icon by icon id
   */
  deleteById(id) {
    try {
      const icon = this.getById(id);
      const icons = JSON.parse(localStorage.getItem(KEY));
      delete icons[id];
      localStorage.setItem(KEY, JSON.stringify(icons));
      return icon;
    } catch (error) {
      throw new Error((0, i18n_exports._)("The icon cannot be deleted."));
    }
  }
};
var LocalIconProvider_default = LocalIconProvider;
//# sourceMappingURL=LocalIconProvider.js.map
