"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getDefaultForm = getDefaultForm;
exports.initialiseFormState = initialiseFormState;
exports.initialiseLabelState = initialiseLabelState;
exports.readCanaryState = readCanaryState;
exports.updateFormState = updateFormState;

var _lodash = require("lodash");

var _url = require("../url");

var _isPlainObject = require("../../../lib/isPlainObject");

var _lists = require("../../Dropdown/lib/lists");

var _labels = require("../labels");

var _excluded = ["layout", "tabBy", "groupBy", "pivotBy", "pivotLabel", "hidePassing", "pivotCellType", "timeRange", "labels"],
    _excluded2 = ["labels"];

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var pivotCellDefaults = new Map([["checkStatuses", null], ["latency", null], ["uptime", null]]);

function getDefaultForm(labels) {
  var incoming = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var initialLabelState = initialiseLabelState(labels, incoming);
  return {
    layout: "table",
    groupBy: "canaryName",
    tabBy: "namespace",
    pivotBy: "none",
    pivotLabel: "",
    timeRange: "1h",
    pivotCellType: "checkStatuses",
    hidePassing: true,
    labels: _objectSpread({}, initialLabelState)
  };
}

function initialiseLabelState(labelMap, incoming) {
  return Object.entries(labelMap).reduce(function (acc, _ref) {
    var _incoming$k;

    var _ref2 = _slicedToArray(_ref, 1),
        k = _ref2[0];

    acc[k] = (_incoming$k = incoming[k]) !== null && _incoming$k !== void 0 ? _incoming$k : 0;
    return acc;
  }, {});
}

function readCanaryState(url) {
  var _decodeUrlSearchParam = (0, _url.decodeUrlSearchParams)(url),
      layout = _decodeUrlSearchParam.layout,
      tabBy = _decodeUrlSearchParam.tabBy,
      groupBy = _decodeUrlSearchParam.groupBy,
      hidePassing = _decodeUrlSearchParam.hidePassing,
      labels = _decodeUrlSearchParam.labels,
      pivotBy = _decodeUrlSearchParam.pivotBy,
      pivotLabel = _decodeUrlSearchParam.pivotLabel,
      pivotCellType = _decodeUrlSearchParam.pivotCellType,
      timeRange = _decodeUrlSearchParam.timeRange;

  var canaryState = _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({
    timeRange: timeRange
  }, layout != null && typeof layout === "string" && {
    layout: layout
  }), tabBy != null && typeof groupBy === "string" && {
    tabBy: tabBy
  }), hidePassing != null && typeof hidePassing === "boolean" && {
    hidePassing: hidePassing
  }), groupBy != null && typeof groupBy === "string" && {
    groupBy: groupBy
  }), pivotBy != null && typeof pivotBy === "string" && {
    pivotBy: pivotBy
  }), pivotCellType != null && typeof pivotCellType === "string" && {
    pivotCellType: pivotCellType
  }), pivotLabel != null && typeof pivotLabel === "string" && {
    pivotLabel: pivotLabel
  }), (0, _isPlainObject.isPlainObject)(labels) && {
    labels: _objectSpread({}, labels)
  });

  return {
    canaryState: canaryState
  };
}

function initialiseFormState(defaultValues, url) {
  var _decodeUrlSearchParam2 = (0, _url.decodeUrlSearchParams)(url),
      layout = _decodeUrlSearchParam2.layout,
      tabBy = _decodeUrlSearchParam2.tabBy,
      groupBy = _decodeUrlSearchParam2.groupBy,
      pivotBy = _decodeUrlSearchParam2.pivotBy,
      pivotLabel = _decodeUrlSearchParam2.pivotLabel,
      hidePassing = _decodeUrlSearchParam2.hidePassing,
      pivotCellType = _decodeUrlSearchParam2.pivotCellType,
      timeRange = _decodeUrlSearchParam2.timeRange,
      _decodeUrlSearchParam3 = _decodeUrlSearchParam2.labels,
      decodedLabels = _decodeUrlSearchParam3 === void 0 ? {} : _decodeUrlSearchParam3,
      rest = _objectWithoutProperties(_decodeUrlSearchParam2, _excluded);

  var pivotByDefaults = new Map(Object.keys(_lists.defaultPivotSelections).map(function (k) {
    return [k, null];
  }));
  var newLabelState = Object.keys(defaultValues.labels).length === 0 ? initialiseLabelState(decodedLabels, decodedLabels) : initialiseLabelState(defaultValues.labels, decodedLabels);
  var labelsFromState = (0, _lists.getLabelsFromState)(newLabelState);
  var labelEntries = Object.entries(labelsFromState.all);
  var nonBooleanlabelEntries = Object.entries(labelsFromState.nonBoolean);
  var groupByDefaults = new Map([["no-group", null], ["description", null], ["name", null]].concat(_toConsumableArray(labelEntries)));
  var pivotLabelDefaults = new Map(_toConsumableArray(nonBooleanlabelEntries));
  var tabByDefaults = new Map([["namespace", null]].concat(_toConsumableArray(Object.entries((0, _labels.getLabelKeys)(defaultValues.labels)))));

  var _nonBooleanlabelEntri = _slicedToArray(nonBooleanlabelEntries, 1),
      first = _nonBooleanlabelEntri[0];

  var _ref3 = first !== null && first !== void 0 ? first : [],
      _ref4 = _slicedToArray(_ref3, 1),
      firstLabel = _ref4[0];

  var groupByValueOrDefault = groupByDefaults.has(groupBy) ? groupBy : "name";
  var tabByValueOrDefault = tabByDefaults.has(tabBy) ? tabBy : "namespace";
  var pivotByValueOrDefault = pivotByDefaults.has(pivotBy) ? pivotBy : "none";
  var pivotCellTypeValueOrDefault = pivotCellDefaults.has(pivotCellType) ? pivotCellType : "checkStatuses";
  var pivotLabelValueOrDefault = pivotLabelDefaults.has(pivotLabel) ? pivotLabel : firstLabel !== null && firstLabel !== void 0 ? firstLabel : "";

  var formState = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, defaultValues), layout != null && typeof layout === "string" && {
    layout: layout
  }), {}, {
    tabBy: tabByValueOrDefault
  }, hidePassing != null && typeof hidePassing === "boolean" && {
    hidePassing: hidePassing
  }), {}, {
    groupBy: groupByValueOrDefault,
    pivotBy: pivotByValueOrDefault,
    pivotLabel: pivotLabelValueOrDefault,
    pivotCellType: pivotCellTypeValueOrDefault,
    labels: newLabelState,
    timeRange: (0, _lodash.isEmpty)(timeRange) || timeRange === "undefined" ? "1h" : timeRange
  });

  return {
    formState: formState,
    fullState: _objectSpread(_objectSpread({}, rest), formState)
  };
}

function updateFormState(update, url, labels) {
  var layout = update.layout,
      timeRange = update.timeRange,
      tabBy = update.tabBy,
      groupBy = update.groupBy,
      pivotBy = update.pivotBy,
      pivotLabel = update.pivotLabel,
      hidePassing = update.hidePassing,
      pivotCellType = update.pivotCellType,
      _update$labels = update.labels,
      updateLabels = _update$labels === void 0 ? {} : _update$labels;

  var _decodeUrlSearchParam4 = (0, _url.decodeUrlSearchParams)(url),
      _decodeUrlSearchParam5 = _decodeUrlSearchParam4.labels,
      decodedLabels = _decodeUrlSearchParam5 === void 0 ? {} : _decodeUrlSearchParam5,
      rest = _objectWithoutProperties(_decodeUrlSearchParam4, _excluded2);

  var incoming = _objectSpread(_objectSpread({}, decodedLabels), updateLabels);

  var newLabels = initialiseLabelState(labels, incoming);
  var pivotByDefaults = new Map(Object.keys(_lists.defaultPivotSelections).map(function (k) {
    return [k, null];
  }));
  var labelsFromState = (0, _lists.getLabelsFromState)(newLabels);
  var labelEntries = Object.entries(labelsFromState.all);
  var nonBooleanlabelEntries = Object.entries(labelsFromState.nonBoolean);
  var pivotLabelDefaults = new Map(_toConsumableArray(nonBooleanlabelEntries));
  var groupByDefaults = new Map([["no-group", null], ["description", null], ["name", null]].concat(_toConsumableArray(labelEntries)));
  var tabByDefaults = new Map([["namespace", null]].concat(_toConsumableArray(Object.entries(labels).map(function (label) {
    return [label[1].key, null];
  }))));

  var _nonBooleanlabelEntri2 = _slicedToArray(nonBooleanlabelEntries, 1),
      first = _nonBooleanlabelEntri2[0];

  var _ref5 = first !== null && first !== void 0 ? first : [],
      _ref6 = _slicedToArray(_ref5, 1),
      firstLabel = _ref6[0];

  var groupByValueOrDefault = groupByDefaults.has(groupBy) ? groupBy : "name";
  var tabByValueOrDefault = tabByDefaults.has(tabBy) ? tabBy : "namespace";
  var pivotByValueOrDefault = pivotByDefaults.has(pivotBy) ? pivotBy : "none";
  var pivotLabelValueOrDefault = pivotLabelDefaults.has(pivotLabel) ? pivotLabel : firstLabel !== null && firstLabel !== void 0 ? firstLabel : "";
  var pivotCellTypeValueOrDefault = pivotCellDefaults.has(pivotCellType) ? pivotCellType : "checkStatuses";

  var formState = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, rest), layout != null && typeof layout === "string" && {
    layout: layout
  }), {}, {
    tabBy: tabByValueOrDefault
  }, hidePassing != null && typeof hidePassing === "boolean" && {
    hidePassing: hidePassing
  }), {}, {
    groupBy: groupByValueOrDefault,
    pivotBy: pivotByValueOrDefault,
    pivotLabel: pivotLabelValueOrDefault,
    pivotCellType: pivotCellTypeValueOrDefault,
    labels: newLabels,
    timeRange: (0, _lodash.isEmpty)(timeRange) || timeRange === "undefined" ? "1h" : timeRange
  });

  return {
    formState: formState
  };
}