const { Callbacks, getJSON, get } = require("jquery");

require([
  "jquery",
  "underscore",
  "splunkjs/mvc",
  "splunkjs/mvc/utils",
  "splunkjs/mvc/searchcontrolsview",
  "splunkjs/mvc/searchmanager",
  "splunkjs/mvc/postprocessmanager",
  "splunkjs/mvc/dropdownview",
  "splunkjs/mvc/multidropdownview",
  "splunkjs/mvc/tableview",
  "splunkjs/mvc/eventsviewerview",
  "splunkjs/mvc/textinputview",
  "splunkjs/mvc/singleview",
  "splunkjs/mvc/chartview",
  "splunkjs/mvc/resultslinkview",
  "splunkjs/mvc/simplexml/searcheventhandler",
  "splunkjs/mvc/visualizationregistry",
  "splunkjs/mvc/simpleform/input/linklist",
  "splunkjs/mvc/simpleform/input/text",
  "splunkjs/mvc/simpleform/input/timerange",
  "splunkjs/mvc/simpleform/input/multiselect",
  "splunkjs/mvc/simpleform/input/dropdown",
  "splunkjs/mvc/simpleform/input/checkboxgroup",
  "splunkjs/mvc/simplexml/element/table",
  "splunkjs/mvc/simplexml/element/single",
  "splunkjs/mvc/simplexml/element/event",
  "splunkjs/mvc/simplexml/element/visualization",
  "splunkjs/mvc/simpleform/formutils",
  "splunkjs/mvc/simplexml/eventhandler",
  "splunkjs/mvc/simplexml/searcheventhandler",
  "splunkjs/mvc/simplexml/ready!",
], function (
  $,
  _,
  mvc,
  utils,
  SearchControlsView,
  SearchManager,
  PostProcessManager,
  DropdownView,
  MultiDropdownView,
  TableView,
  EventsViewer,
  TextInputView,
  SingleView,
  ChartView,
  ResultsLinkView,
  SearchEventHandler,
  VisualizationRegistry,
  LinkListInput,
  TextInput,
  TimeRangeInput,
  MultiSelectInput,
  DropdownInput,
  CheckboxGroupInput,
  TableElement,
  VisualizationElement,
  SingleElement,
  EventElement,
  FormUtils,
  EventHandler,
  SearchEventHandler
) {
  //
  // START
  //

  // tokens

  var defaultTokenModel = mvc.Components.getInstance("default", {
    create: true,
  });
  var submittedTokenModel = mvc.Components.getInstance("submitted", {
    create: true,
  });

  function setToken(name, value) {
    defaultTokenModel.set(name, value);
    submittedTokenModel.set(name, value);
  }

  function getToken(name) {
    var ret = null;
    if (defaultTokenModel.get(name) != undefined) {
      ret = defaultTokenModel.get(name);
    } else if (submittedTokenModel.get(name) != undefined) {
      ret = submittedTokenModel.get(name);
    }
    return ret;
  }

  function unsetToken(name) {
    defaultTokenModel.unset(name);
    submittedTokenModel.unset(name);
  }

  // close all opened modals
  function closeModals() {
    $(".modal").modal("hide");
  }

  // Returns true if numeric
  function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n) && n > 0;
  }

  // searches

  var search1 = new SearchManager(
    {
      id: "search1",
      earliest_time: "-5m",
      sample_ratio: 1,
      status_buckets: 0,
      cancelOnUnload: true,
      latest_time: "now",
      search: "| inputlookup nmon_alerting_threshold_template | stats count",
      app: utils.getCurrentApp(),
      auto_cancel: 90,
      preview: true,
      runWhenTimeIsUndefined: false,
    },
    { tokens: true, tokenNamespace: "submitted" }
  );

  var search2 = new SearchManager(
    {
      id: "search2",
      earliest_time: "-5m",
      status_buckets: 0,
      sample_ratio: 1,
      latest_time: "now",
      cancelOnUnload: true,
      search:
        "| inputlookup nmon_alerting_threshold_template | search frameID=$search_frameID$ | eval KeyID = _key | table KeyID,frameID,* | eval max_cpu_percent=alert_cpu_max_percent, max_phy_percent=alert_physical_memory_max_percent, max_vir_percent=alert_virtual_memory_max_percent",
      app: utils.getCurrentApp(),
      auto_cancel: 90,
      preview: true,
      runWhenTimeIsUndefined: false,
    },
    { tokens: true, tokenNamespace: "submitted" }
  );

  var search3 = new SearchManager(
    {
      id: "search3",
      earliest_time: "-5m",
      status_buckets: 0,
      sample_ratio: 1,
      latest_time: "now",
      cancelOnUnload: true,
      search:
        "| inputlookup nmon_alerting_threshold_template | stats dc(frameID) as frameID",
      app: utils.getCurrentApp(),
      auto_cancel: 90,
      preview: true,
      runWhenTimeIsUndefined: false,
    },
    { tokens: true, tokenNamespace: "submitted" }
  );

  var search4 = new SearchManager(
    {
      id: "search4",
      earliest_time: "-5m",
      status_buckets: 0,
      sample_ratio: 1,
      latest_time: "now",
      cancelOnUnload: true,
      search:
        "| inputlookup nmon_frameID_mapping | search frameID=$input_frameID_search_frameid$ serialnum=$input_frameID_search_serialnum$ host=$input_frameID_search_host$ host_description=$input_frameID_search_host_description$ | table frameID,serialnum,host,host_description,*",
      app: utils.getCurrentApp(),
      auto_cancel: 90,
      preview: true,
      runWhenTimeIsUndefined: false,
    },
    { tokens: true, tokenNamespace: "submitted" }
  );

  function updateAllSearches() {
    search1.startSearch();
    search2.startSearch();
    search3.startSearch();
    search4.startSearch();
  }

  // single views

  var element_unset_exclusions = new SingleView(
    {
      id: "element_unset_exclusions",
      unitPosition: "after",
      numberPrecision: "0",
      drilldown: "all",
      useColors: "1",
      trendDisplayMode: "absolute",
      rangeValues: "[0]",
      colorBy: "value",
      showTrendIndicator: "1",
      showSparkline: "1",
      colorMode: "none",
      trendColorInterpretation: "standard",
      underLabel: "Number of threshold configured",
      useThousandSeparators: "1",
      rangeColors: '["0x3F6FDE","0x3F6FDE"]',
      managerid: "search1",
      el: $("#element_unset_exclusions"),
    },
    { tokens: true, tokenNamespace: "submitted" }
  ).render();

  var element_nb_hosts = new SingleView(
    {
      id: "element_nb_hosts",
      unitPosition: "after",
      numberPrecision: "0",
      drilldown: "all",
      useColors: "1",
      trendDisplayMode: "absolute",
      rangeValues: "[0]",
      colorBy: "value",
      showTrendIndicator: "1",
      showSparkline: "1",
      colorMode: "none",
      trendColorInterpretation: "standard",
      underLabel: "Number of frameID with threshold configured",
      useThousandSeparators: "1",
      rangeColors: '["0x3F6FDE","0x3F6FDE"]',
      managerid: "search3",
      el: $("#element_nb_hosts"),
    },
    { tokens: true, tokenNamespace: "submitted" }
  ).render();

  // link input
  var inputLink = new LinkListInput(
    {
      id: "inputLink",
      choices: [
        {
          value: "template_thresholds",
          label: "Template thresholds collection",
        },
        {
          value: "frameid_collection",
          label: "FrameID current collection",
        },
      ],
      default: "template_thresholds",
      searchWhenChanged: true,
      selectFirstChoice: false,
      initialValue: "template_thresholds",
      value: "$form.inputLink$",
      el: $("#inputLink"),
    },
    {
      tokens: true,
    }
  ).render();

  inputLink.on("change", function (newValue) {
    setToken("inputLink", newValue);
  });

  inputLink.on("valueChange", function (e) {
    if (e.value === "template_thresholds") {
      // show and hide elements
      $("#tableParent1").css("display", "inherit");
      $("#tableParent2").css("display", "none");
    } else if (e.value === "frameid_collection") {
      // show and hide elements
      $("#tableParent1").css("display", "none");
      $("#tableParent2").css("display", "inherit");
    }
  });

  // tables

  var element_table_show_lookup_content = new TableElement(
    {
      id: "element_table_show_lookup_content",
      count: 10,
      dataOverlayMode: "none",
      drilldown: "row",
      percentagesRow: "false",
      rowNumbers: "false",
      totalsRow: "false",
      wrap: "true",
      managerid: "search2",
      el: $("#element_table_show_lookup_content"),
    },
    { tokens: true, tokenNamespace: "submitted" }
  ).render();

  element_table_show_lookup_content.on("click", function (e) {
    if (e.field !== undefined) {
      e.preventDefault();
      // set tk_keyid
      setToken("tk_keyid", e.data["row.KeyID"]);
      // Populate input forms
      setToken("form.input_update_frameid", e.data["row.frameID"]);
      setToken(
        "form.input_update_alert_cpu_max_percent",
        e.data["row.alert_cpu_max_percent"]
      );
      setToken(
        "form.input_update_alert_cpu_min_time_seconds",
        e.data["row.alert_cpu_min_time_seconds"]
      );
      setToken(
        "form.input_update_alert_physical_memory_max_percent",
        e.data["row.alert_physical_memory_max_percent"]
      );
      setToken(
        "form.input_update_alert_physical_memory_min_time_seconds",
        e.data["row.alert_physical_memory_min_time_seconds"]
      );
      setToken(
        "form.input_update_alert_virtual_memory_max_percent",
        e.data["row.alert_virtual_memory_max_percent"]
      );
      setToken(
        "form.input_update_alert_virtual_memory_min_time_seconds",
        e.data["row.alert_virtual_memory_min_time_seconds"]
      );
      $("#modal_update_entity").modal();
    }
  });

  var element_table_show_frameID_lookup_content = new TableElement(
    {
      id: "element_table_show_frameID_lookup_content",
      count: 10,
      dataOverlayMode: "none",
      drilldown: "none",
      percentagesRow: "false",
      rowNumbers: "false",
      totalsRow: "false",
      wrap: "true",
      managerid: "search4",
      el: $("#element_table_show_frameID_lookup_content"),
    },
    { tokens: true, tokenNamespace: "submitted" }
  ).render();

  // inputs for template search purposes

  var input_search_frameid = new TextInput(
    {
      id: "input_search_frameid",
      value: "$form.search_frameID$",
      default: "*",
      searchWhenChanged: true,
      el: $("#input_search_frameid"),
    },
    { tokens: true }
  ).render();

  input_search_frameid.on("change", function (newValue) {
    setToken("search_frameID", newValue);
  });

  // search frameID mapping

  var input_frameID_search_frameid = new TextInput(
    {
      id: "input_frameID_search_frameid",
      value: "$form.input_frameID_search_frameid$",
      default: "*",
      searchWhenChanged: true,
      el: $("#input_frameID_search_frameid"),
    },
    { tokens: true }
  ).render();

  input_frameID_search_frameid.on("change", function (newValue) {
    setToken("input_frameID_search_frameid", newValue);
  });

  var input_frameID_search_serialnum = new TextInput(
    {
      id: "input_frameID_search_serialnum",
      value: "$form.input_frameID_search_serialnum$",
      default: "*",
      searchWhenChanged: true,
      el: $("#input_frameID_search_serialnum"),
    },
    { tokens: true }
  ).render();

  input_frameID_search_serialnum.on("change", function (newValue) {
    setToken("input_frameID_search_serialnum", newValue);
  });

  var input_frameID_search_host = new TextInput(
    {
      id: "input_frameID_search_host",
      value: "$form.input_frameID_search_host$",
      default: "*",
      searchWhenChanged: true,
      el: $("#input_frameID_search_host"),
    },
    { tokens: true }
  ).render();

  input_frameID_search_host.on("change", function (newValue) {
    setToken("input_frameID_search_host", newValue);
  });

  var input_frameID_search_host_description = new TextInput(
    {
      id: "input_frameID_search_host_description",
      value: "$form.input_frameID_search_host_description$",
      default: "*",
      searchWhenChanged: true,
      el: $("#input_frameID_search_host_description"),
    },
    { tokens: true }
  ).render();

  input_frameID_search_host_description.on("change", function (newValue) {
    setToken("input_frameID_search_host_description", newValue);
  });

  // add new entries

  var input_add_frameid = new TextInput(
    {
      id: "input_add_frameid",
      value: "$form.input_add_frameid$",
      el: $("#input_add_frameid"),
    },
    { tokens: true }
  ).render();

  input_add_frameid.on("change", function (newValue) {
    setToken("input_add_frameid", newValue);
  });

  var input_add_alert_cpu_max_percent = new TextInput(
    {
      id: "input_add_alert_cpu_max_percent",
      value: "$form.input_add_alert_cpu_max_percent$",
      default: "90",
      el: $("#input_add_alert_cpu_max_percent"),
    },
    { tokens: true }
  ).render();

  input_add_alert_cpu_max_percent.on("change", function (newValue) {
    setToken("input_add_alert_cpu_max_percent", newValue);
  });

  var input_add_alert_cpu_min_time_seconds = new TextInput(
    {
      id: "input_add_alert_cpu_min_time_seconds",
      value: "$form.input_add_alert_cpu_min_time_seconds$",
      default: "300",
      el: $("#input_add_alert_cpu_min_time_seconds"),
    },
    { tokens: true }
  ).render();

  input_add_alert_cpu_min_time_seconds.on("change", function (newValue) {
    setToken("input_add_alert_cpu_min_time_seconds", newValue);
  });

  var input_add_alert_physical_memory_max_percent = new TextInput(
    {
      id: "input_add_alert_physical_memory_max_percent",
      value: "$form.input_add_alert_physical_memory_max_percent$",
      default: "90",
      el: $("#input_add_alert_physical_memory_max_percent"),
    },
    { tokens: true }
  ).render();

  input_add_alert_physical_memory_max_percent.on("change", function (newValue) {
    setToken("input_add_alert_physical_memory_max_percent", newValue);
  });

  var input_add_alert_physical_memory_min_time_seconds = new TextInput(
    {
      id: "input_add_alert_physical_memory_min_time_seconds",
      value: "$form.input_add_alert_physical_memory_min_time_seconds$",
      default: "300",
      el: $("#input_add_alert_physical_memory_min_time_seconds"),
    },
    { tokens: true }
  ).render();

  input_add_alert_physical_memory_min_time_seconds.on(
    "change",
    function (newValue) {
      setToken("input_add_alert_physical_memory_min_time_seconds", newValue);
    }
  );

  var input_add_alert_virtual_memory_max_percent = new TextInput(
    {
      id: "input_add_alert_virtual_memory_max_percent",
      value: "$form.input_add_alert_virtual_memory_max_percent$",
      default: "40",
      el: $("#input_add_alert_virtual_memory_max_percent"),
    },
    { tokens: true }
  ).render();

  input_add_alert_virtual_memory_max_percent.on("change", function (newValue) {
    setToken("input_add_alert_virtual_memory_max_percent", newValue);
  });

  var input_add_alert_virtual_memory_min_time_seconds = new TextInput(
    {
      id: "input_add_alert_virtual_memory_min_time_seconds",
      value: "$form.input_add_alert_virtual_memory_min_time_seconds$",
      default: "300",
      el: $("#input_add_alert_virtual_memory_min_time_seconds"),
    },
    { tokens: true }
  ).render();

  input_add_alert_virtual_memory_min_time_seconds.on(
    "change",
    function (newValue) {
      setToken("input_add_alert_virtual_memory_min_time_seconds", newValue);
    }
  );

  // update entries
  var input_update_frameid = new TextInput(
    {
      id: "input_update_frameid",
      value: "$form.input_update_frameid$",
      el: $("#input_update_frameid"),
    },
    { tokens: true }
  ).render();

  input_update_frameid.on("change", function (newValue) {
    setToken("input_update_frameid", newValue);
  });

  var input_update_alert_cpu_max_percent = new TextInput(
    {
      id: "input_update_alert_cpu_max_percent",
      value: "$form.input_update_alert_cpu_max_percent$",
      default: "90",
      el: $("#input_update_alert_cpu_max_percent"),
    },
    { tokens: true }
  ).render();

  input_update_alert_cpu_max_percent.on("change", function (newValue) {
    setToken("input_update_alert_cpu_max_percent", newValue);
  });

  var input_update_alert_cpu_min_time_seconds = new TextInput(
    {
      id: "input_update_alert_cpu_min_time_seconds",
      value: "$form.input_update_alert_cpu_min_time_seconds$",
      default: "300",
      el: $("#input_update_alert_cpu_min_time_seconds"),
    },
    { tokens: true }
  ).render();

  input_update_alert_cpu_min_time_seconds.on("change", function (newValue) {
    setToken("input_update_alert_cpu_min_time_seconds", newValue);
  });

  var input_update_alert_physical_memory_max_percent = new TextInput(
    {
      id: "input_update_alert_physical_memory_max_percent",
      value: "$form.input_update_alert_physical_memory_max_percent$",
      default: "90",
      el: $("#input_update_alert_physical_memory_max_percent"),
    },
    { tokens: true }
  ).render();

  input_update_alert_physical_memory_max_percent.on(
    "change",
    function (newValue) {
      setToken("input_update_alert_physical_memory_max_percent", newValue);
    }
  );

  var input_update_alert_physical_memory_min_time_seconds = new TextInput(
    {
      id: "input_update_alert_physical_memory_min_time_seconds",
      value: "$form.input_update_alert_physical_memory_min_time_seconds$",
      default: "300",
      el: $("#input_update_alert_physical_memory_min_time_seconds"),
    },
    { tokens: true }
  ).render();

  input_update_alert_physical_memory_min_time_seconds.on(
    "change",
    function (newValue) {
      setToken("input_update_alert_physical_memory_min_time_seconds", newValue);
    }
  );

  var input_update_alert_virtual_memory_max_percent = new TextInput(
    {
      id: "input_update_alert_virtual_memory_max_percent",
      value: "$form.input_update_alert_virtual_memory_max_percent$",
      default: "40",
      el: $("#input_update_alert_virtual_memory_max_percent"),
    },
    { tokens: true }
  ).render();

  input_update_alert_virtual_memory_max_percent.on(
    "change",
    function (newValue) {
      setToken("input_update_alert_virtual_memory_max_percent", newValue);
    }
  );

  var input_update_alert_virtual_memory_min_time_seconds = new TextInput(
    {
      id: "input_update_alert_virtual_memory_min_time_seconds",
      value: "$form.input_update_alert_virtual_memory_min_time_seconds$",
      default: "300",
      el: $("#input_update_alert_virtual_memory_min_time_seconds"),
    },
    { tokens: true }
  ).render();

  input_update_alert_virtual_memory_min_time_seconds.on(
    "change",
    function (newValue) {
      setToken("input_update_alert_virtual_memory_min_time_seconds", newValue);
    }
  );

  // interactions

  // help
  $("#btn_help")
    .unbind()
    .click(function () {
      $("#modal_help").modal();
    });

  // add new entry
  $("#btn_add_new_template")
    .unbind()
    .click(function () {
      $("#modal_add_entity").modal();
    });

  // submit new entry
  $("#btn_submit_new_entity").click(function () {
    var frameID = getToken("input_add_frameid");
    var alert_cpu_max_percent = getToken("input_add_alert_cpu_max_percent");
    var alert_cpu_min_time_seconds = getToken(
      "input_add_alert_cpu_min_time_seconds"
    );
    var alert_physical_memory_max_percent = getToken(
      "input_add_alert_physical_memory_max_percent"
    );
    var alert_physical_memory_min_time_seconds = getToken(
      "input_add_alert_physical_memory_min_time_seconds"
    );
    var alert_virtual_memory_max_percent = getToken(
      "input_add_alert_virtual_memory_max_percent"
    );
    var alert_virtual_memory_min_time_seconds = getToken(
      "input_add_alert_virtual_memory_min_time_seconds"
    );

    // new record
    record = {
      frameID: frameID,
      alert_cpu_max_percent: alert_cpu_max_percent,
      alert_cpu_min_time_seconds: alert_cpu_min_time_seconds,
      alert_physical_memory_max_percent: alert_physical_memory_max_percent,
      alert_physical_memory_min_time_seconds:
        alert_physical_memory_min_time_seconds,
      alert_virtual_memory_max_percent: alert_virtual_memory_max_percent,
      alert_virtual_memory_min_time_seconds:
        alert_virtual_memory_min_time_seconds,
    };

    // Create the endpoint URL
    var myendpoint_URl =
      "/en-US/splunkd/__raw/servicesNS/nobody/metricator-for-nmon/storage/collections/data/kv_nmon_alerting_threshold_template/";

    if (
      frameID &&
      frameID.length &&
      alert_cpu_max_percent &&
      alert_cpu_max_percent.length &&
      isNumeric(alert_cpu_max_percent) &&
      alert_cpu_min_time_seconds &&
      alert_cpu_min_time_seconds.length &&
      isNumeric(alert_cpu_min_time_seconds) &&
      alert_physical_memory_max_percent &&
      alert_physical_memory_max_percent.length &&
      isNumeric(alert_physical_memory_max_percent) &&
      alert_physical_memory_min_time_seconds &&
      alert_physical_memory_min_time_seconds.length &&
      isNumeric(alert_physical_memory_min_time_seconds) &&
      alert_virtual_memory_max_percent &&
      alert_virtual_memory_max_percent.length &&
      isNumeric(alert_virtual_memory_max_percent) &&
      alert_virtual_memory_min_time_seconds &&
      alert_virtual_memory_min_time_seconds.length &&
      isNumeric(alert_virtual_memory_min_time_seconds)
    ) {
      $.ajax({
        url: myendpoint_URl,
        type: "POST",
        async: true,
        contentType: "application/json",
        data: JSON.stringify(record),
        success: function (returneddata) {
          // Return to modal
          $("#modal_generic_success").modal();
          // update searches
          updateAllSearches();
        },
        error: function (xhr, textStatus, error) {
          message = "Error Updating!" + xhr + textStatus + error;
          // Hide main modal
          closeModals();
          $("#modal_generic_error")
            .find(".modal-error-message p")
            .text(message);
          $("#modal_generic_error").modal();
        },
      });
    } else {
      message =
        "Error Updating! Please check your inputs: " + JSON.stringify(record);
      // Hide main modal
      closeModals();
      $("#modal_generic_error").find(".modal-error-message p").text(message);
      $("#modal_generic_error").modal();
    }
  });

  // delete entity
  $("#btn_submit_delete_entity").click(function () {
    var tk_keyid = getToken("tk_keyid");

    // Create the endpoint URL
    var myendpoint_URl =
      "/en-US/splunkd/__raw/servicesNS/nobody/metricator-for-nmon/storage/collections/data/kv_nmon_alerting_threshold_template/" +
      tk_keyid;

    if (tk_keyid && tk_keyid.length) {
      $.ajax({
        url: myendpoint_URl,
        type: "DELETE",
        async: true,
        contentType: "application/json",
        success: function (returneddata) {
          // Return to modal
          $("#modal_generic_success").modal();
          // update searches
          updateAllSearches();
        },
        error: function (xhr, textStatus, error) {
          message = "Error Updating!" + xhr + textStatus + error;
          // Hide main modal
          closeModals();
          $("#modal_generic_error")
            .find(".modal-error-message p")
            .text(message);
          $("#modal_generic_error").modal();
        },
      });
    }
  });

  // update entry
  $("#btn_submit_update_entity").click(function () {
    var tk_keyid = getToken("tk_keyid");
    var frameID = getToken("input_update_frameid");
    var alert_cpu_max_percent = getToken("input_update_alert_cpu_max_percent");
    var alert_cpu_min_time_seconds = getToken(
      "input_update_alert_cpu_min_time_seconds"
    );
    var alert_physical_memory_max_percent = getToken(
      "input_update_alert_physical_memory_max_percent"
    );
    var alert_physical_memory_min_time_seconds = getToken(
      "input_update_alert_physical_memory_min_time_seconds"
    );
    var alert_virtual_memory_max_percent = getToken(
      "input_update_alert_virtual_memory_max_percent"
    );
    var alert_virtual_memory_min_time_seconds = getToken(
      "input_update_alert_virtual_memory_min_time_seconds"
    );

    // new record
    record = {
      frameID: frameID,
      alert_cpu_max_percent: alert_cpu_max_percent,
      alert_cpu_min_time_seconds: alert_cpu_min_time_seconds,
      alert_physical_memory_max_percent: alert_physical_memory_max_percent,
      alert_physical_memory_min_time_seconds:
        alert_physical_memory_min_time_seconds,
      alert_virtual_memory_max_percent: alert_virtual_memory_max_percent,
      alert_virtual_memory_min_time_seconds:
        alert_virtual_memory_min_time_seconds,
    };

    // Create the endpoint URL
    var myendpoint_URl =
      "/en-US/splunkd/__raw/servicesNS/nobody/metricator-for-nmon/storage/collections/data/kv_nmon_alerting_threshold_template/" +
      tk_keyid;

    if (
      frameID &&
      frameID.length &&
      alert_cpu_max_percent &&
      alert_cpu_max_percent.length &&
      isNumeric(alert_cpu_max_percent) &&
      alert_cpu_min_time_seconds &&
      alert_cpu_min_time_seconds.length &&
      isNumeric(alert_cpu_min_time_seconds) &&
      alert_physical_memory_max_percent &&
      alert_physical_memory_max_percent.length &&
      isNumeric(alert_physical_memory_max_percent) &&
      alert_physical_memory_min_time_seconds &&
      alert_physical_memory_min_time_seconds.length &&
      isNumeric(alert_physical_memory_min_time_seconds) &&
      alert_virtual_memory_max_percent &&
      alert_virtual_memory_max_percent.length &&
      isNumeric(alert_virtual_memory_max_percent) &&
      alert_virtual_memory_min_time_seconds &&
      alert_virtual_memory_min_time_seconds.length &&
      isNumeric(alert_virtual_memory_min_time_seconds)
    ) {
      $.ajax({
        url: myendpoint_URl,
        type: "POST",
        async: true,
        contentType: "application/json",
        data: JSON.stringify(record),
        success: function (returneddata) {
          // Return to modal
          $("#modal_generic_success").modal();
          // update searches
          updateAllSearches();
        },
        error: function (xhr, textStatus, error) {
          message = "Error Updating!" + xhr + textStatus + error;
          // Hide main modal
          closeModals();
          $("#modal_generic_error")
            .find(".modal-error-message p")
            .text(message);
          $("#modal_generic_error").modal();
        },
      });
    } else {
      message =
        "Error Updating! Please check your inputs: " + JSON.stringify(record);
      // Hide main modal
      closeModals();
      $("#modal_generic_error").find(".modal-error-message p").text(message);
      $("#modal_generic_error").modal();
    }
  });

  //
  // END
  //
});
