"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LogsPage = LogsPage;
exports.logTypes = void 0;

var _solid = require("@heroicons/react/solid");

var _lodash = require("lodash");

var _reactHookForm = require("react-hook-form");

var _bs = require("react-icons/bs");

var _react = _interopRequireWildcard(require("react"));

var _reactRouterDom = require("react-router-dom");

var _logs = require("../api/services/logs");

var _topology = require("../api/services/topology");

var _Dropdown = require("../components/Dropdown");

var _Layout = require("../components/Layout");

var _Loading = require("../components/Loading");

var _Logs = require("../components/Logs");

var _TextInput = require("../components/TextInput");

var _TimeRange = require("../components/Dropdown/TimeRange");

var _RefreshButton = require("../components/RefreshButton");

var _jsxRuntime = require("react/jsx-runtime");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { 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; }

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

var logTypes = [{
  icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_bs.BsGridFill, {}),
  description: "Node",
  value: "KubernetesNode"
}, {
  icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_bs.BsGearFill, {}),
  description: "Service",
  value: "KubernetesService"
}, {
  icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_bs.BsFlower2, {}),
  description: "Pod",
  value: "KubernetesPod"
}, {
  icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_bs.BsStack, {}),
  description: "VM",
  value: "VM"
}];
exports.logTypes = logTypes;

function LogsPage() {
  var _useState = (0, _react.useState)(true),
      _useState2 = _slicedToArray(_useState, 2),
      logsIsLoading = _useState2[0],
      setLogsIsLoading = _useState2[1];

  var _useSearchParams = (0, _reactRouterDom.useSearchParams)(),
      _useSearchParams2 = _slicedToArray(_useSearchParams, 2),
      searchParams = _useSearchParams2[0],
      setSearchParams = _useSearchParams2[1];

  var _useState3 = (0, _react.useState)(searchParams.get("query")),
      _useState4 = _slicedToArray(_useState3, 2),
      query = _useState4[0],
      setQuery = _useState4[1]; // eslint-disable-next-line no-unused-vars


  var _useState5 = (0, _react.useState)(searchParams.get("topologyId")),
      _useState6 = _slicedToArray(_useState5, 2),
      topologyId = _useState6[0],
      setTopologyId = _useState6[1];

  var _useState7 = (0, _react.useState)(searchParams.get("externalId")),
      _useState8 = _slicedToArray(_useState7, 2),
      externalId = _useState8[0],
      setExternalId = _useState8[1];

  var _useState9 = (0, _react.useState)(null),
      _useState10 = _slicedToArray(_useState9, 2),
      topology = _useState10[0],
      setTopology = _useState10[1];

  var _useState11 = (0, _react.useState)([]),
      _useState12 = _slicedToArray(_useState11, 2),
      logs = _useState12[0],
      setLogs = _useState12[1];

  var _useForm = (0, _reactHookForm.useForm)({
    defaultValues: {
      type: searchParams.get("type") || logTypes[0].value,
      start: searchParams.get("start") || _TimeRange.timeRanges[0].value
    }
  }),
      control = _useForm.control,
      getValues = _useForm.getValues;

  (0, _react.useEffect)(function () {
    if (topologyId != null && topology == null) {
      (0, _topology.getTopology)({
        id: topologyId
      }).then(function (topology) {
        var result = topology.data[0];

        if ((0, _lodash.isEmpty)(result.id) && result.components != null && result.components.length === 1) {
          setTopology(result.components[0]);
        } else {
          setTopology(result);
        }
      });
    }
  }, [topology, topologyId]);

  var saveQueryParams = function saveQueryParams() {
    var paramsList = _objectSpread({
      query: query,
      topologyId: topologyId,
      externalId: externalId
    }, getValues());

    var params = {};
    Object.entries(paramsList).forEach(function (_ref) {
      var _ref2 = _slicedToArray(_ref, 2),
          key = _ref2[0],
          value = _ref2[1];

      if (value) {
        params[key] = value;
      }
    });
    setSearchParams(params);
  }; // eslint-disable-next-line react-hooks/exhaustive-deps


  var loadLogs = (0, _react.useCallback)(function () {
    saveQueryParams();
    setLogsIsLoading(true);

    var queryBody = _objectSpread({
      query: query,
      id: externalId
    }, getValues());

    (0, _logs.getLogs)(queryBody).then(function (res) {
      if (res.data != null) {
        setLogs(res.data.results);
      }

      setLogsIsLoading(false);
    });
  });
  (0, _react.useEffect)(function () {
    loadLogs();
  }, [loadLogs, topologyId]);

  if (!(0, _lodash.isEmpty)(topologyId) && topology == null) {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Loading.Loading, {
      text: "Loading topology ".concat(topologyId)
    });
  }

  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layout.SearchLayout, {
    title: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("h1", {
        className: "text-xl font-semibold",
        children: ["Logs", topology != null && /*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
          className: "text-gray-600",
          children: ["/ ", topology.name || topology.text]
        })]
      })
    }),
    extra: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.Dropdown, {
        control: control,
        name: "type",
        className: "w-36 mr-2 flex-shrink-0",
        items: logTypes
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "mr-2 w-full relative rounded-md shadow-sm",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "absolute inset-y-0 left-0 pl-3 flex items-center",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
            type: "button",
            onClick: function onClick() {
              return loadLogs();
            },
            className: "hover",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_bs.BsListOl, {
              className: "h-5 w-5 text-gray-400 hover:text-gray-600",
              "aria-hidden": "true"
            })
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_TextInput.TextInput, {
          placeholder: "External ID",
          className: "pl-10 pb-2.5 w-full flex-shrink-0",
          style: {
            height: "38px"
          },
          id: "externalId",
          onChange: function onChange(e) {
            e.preventDefault();
            setExternalId(e.target.value);
          },
          onEnter: function onEnter() {
            return loadLogs();
          },
          value: externalId
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_RefreshButton.RefreshButton, {
        onClick: function onClick() {
          return loadLogs();
        }
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "mr-2 w-full relative rounded-md shadow-sm",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "absolute inset-y-0 left-0 pl-3 flex items-center",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
            type: "button",
            onClick: function onClick() {
              return loadLogs();
            },
            className: "hover",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_solid.SearchIcon, {
              className: "h-5 w-5 text-gray-400 hover:text-gray-600",
              "aria-hidden": "true"
            })
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_TextInput.TextInput, {
          placeholder: "Search",
          className: "pl-10 pb-2.5 w-full flex-shrink-0",
          style: {
            height: "38px"
          },
          id: "searchQuery",
          onEnter: function onEnter() {
            return loadLogs();
          },
          onChange: function onChange(e) {
            e.preventDefault();
            setQuery(e.target.value);
          },
          value: query
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.Dropdown, {
        control: control,
        name: "start",
        className: "w-40 mr-2 flex-shrink-0",
        items: _TimeRange.timeRanges
      })]
    }),
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Logs.LogsViewer, {
      logs: logs,
      isLoading: logsIsLoading
    })
  });
}