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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
import React, { useEffect, useState } from 'react';
import { Empty, Spin } from 'antd';
import { Icon, PisellModal } from '@pisell/materials';
import { CloseOutlined } from '@ant-design/icons';
import { getDeviceConnections, getDeviceDetail } from "../../../api";
import { createDeviceRow } from "../../../model";
import { DEVICE_ICON_COLOR, getConnectionTypeLabel } from "../../../shared";
import DeviceInfoPanel from "../../deviceDetail/components/DeviceInfoPanel";
import ConnectionDeviceCard from "./ConnectionDeviceCard";
var getStatusTone = function getStatusTone(value) {
  if (value === 'online' || value === 'connected' || value === 'linked') {
    return 'success';
  }
  if (value === 'connecting') return 'processing';
  if (value === 'unlinked') return 'warning';
  if (value === 'disconnected') return 'error';
  return 'default';
};
var getDataValue = function getDataValue(data, key) {
  if (!data) return undefined;
  var value = data[key];
  if (value == null || _typeof(value) === 'object') return undefined;
  return String(value);
};
var getNetworkLocalIp = function getNetworkLocalIp(data) {
  var network = data === null || data === void 0 ? void 0 : data.network;
  if (!network || _typeof(network) !== 'object' || Array.isArray(network)) {
    return undefined;
  }
  return getDataValue(network, 'local_ip');
};
var getConnectionLines = function getConnectionLines(connection) {
  var _connection$config;
  var connectionType = getConnectionTypeLabel((_connection$config = connection.config) === null || _connection$config === void 0 ? void 0 : _connection$config.connection_type);
  var parts = [connectionType === '-' ? undefined : connectionType];
  var connectionData = connection.data;
  var ip = getDataValue(connectionData, 'ip') || getNetworkLocalIp(connectionData);
  var port = getDataValue(connectionData, 'port');
  var macAddress = getDataValue(connectionData, 'mac');
  if (ip) parts.push("IP: ".concat(ip));
  if (port) parts.push("Port: ".concat(port));
  if (macAddress) parts.push("MAC: ".concat(macAddress));
  return parts.filter(Boolean).length ? [parts.filter(Boolean).join(' · ')] : [];
};
var ConnectedDevicePreviewModal = function ConnectedDevicePreviewModal(_ref) {
  var _detailDevice$type;
  var open = _ref.open,
    device = _ref.device,
    connectionType = _ref.connectionType,
    getText = _ref.getText,
    translation = _ref.translation,
    onClose = _ref.onClose;
  var _useState = useState(device),
    _useState2 = _slicedToArray(_useState, 2),
    detailDevice = _useState2[0],
    setDetailDevice = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    connections = _useState4[0],
    setConnections = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    loading = _useState6[0],
    setLoading = _useState6[1];
  var record = createDeviceRow(detailDevice, translation);
  var getStatusLabel = function getStatusLabel(value) {
    if (!value) return '-';
    var key = "pisell2.saas.device-planning.status.".concat(value);
    var text = getText(key);
    return text && text !== key ? text : value;
  };
  useEffect(function () {
    if (!open || !device.id) return;
    var cancelled = false;
    setDetailDevice(device);
    setConnections([]);
    setLoading(true);
    Promise.all([getDeviceDetail(device.id), getDeviceConnections({
      type: connectionType,
      target_device_id: device.id,
      with: ['sourceDevice.type', 'sourceDevice.model.brand', 'sourceDevice.workarea', 'profiles']
    })]).then(function (_ref2) {
      var _ref3 = _slicedToArray(_ref2, 2),
        detail = _ref3[0],
        list = _ref3[1];
      if (cancelled) return;
      setDetailDevice(detail || device);
      setConnections(list);
    }).catch(function () {
      if (cancelled) return;
      setDetailDevice(device);
      setConnections([]);
    }).finally(function () {
      if (!cancelled) {
        setLoading(false);
      }
    });
    return function () {
      cancelled = true;
    };
  }, [connectionType, device, device.id, open]);
  var renderConnectionItem = function renderConnectionItem(connection) {
    var _smartDevice$type, _smartDevice$model, _smartDevice$model2, _smartDevice$model3, _smartDevice$type2;
    var smartDevice = connection.source_device;
    return /*#__PURE__*/React.createElement(ConnectionDeviceCard, {
      key: connection.id,
      title: smartDevice ? translation(smartDevice.name) || smartDevice.id : '-',
      deviceInfo: {
        icon: (smartDevice === null || smartDevice === void 0 || (_smartDevice$type = smartDevice.type) === null || _smartDevice$type === void 0 ? void 0 : _smartDevice$type.icon) || 'DesktopOutlined',
        modelName: translation(smartDevice === null || smartDevice === void 0 || (_smartDevice$model = smartDevice.model) === null || _smartDevice$model === void 0 ? void 0 : _smartDevice$model.name) || (smartDevice === null || smartDevice === void 0 ? void 0 : smartDevice.model_code) || '-',
        brandName: translation(smartDevice === null || smartDevice === void 0 || (_smartDevice$model2 = smartDevice.model) === null || _smartDevice$model2 === void 0 || (_smartDevice$model2 = _smartDevice$model2.brand) === null || _smartDevice$model2 === void 0 ? void 0 : _smartDevice$model2.name) || (smartDevice === null || smartDevice === void 0 || (_smartDevice$model3 = smartDevice.model) === null || _smartDevice$model3 === void 0 ? void 0 : _smartDevice$model3.brand_code) || '-',
        typeName: translation(smartDevice === null || smartDevice === void 0 || (_smartDevice$type2 = smartDevice.type) === null || _smartDevice$type2 === void 0 ? void 0 : _smartDevice$type2.name) || (smartDevice === null || smartDevice === void 0 ? void 0 : smartDevice.type_code) || '-',
        statusLines: []
      },
      connectionInfo: {
        lines: getConnectionLines(connection)
      },
      deviceStatuses: [{
        key: 'link',
        label: getStatusLabel((smartDevice === null || smartDevice === void 0 ? void 0 : smartDevice.link) || 'unconnected'),
        tone: getStatusTone((smartDevice === null || smartDevice === void 0 ? void 0 : smartDevice.link) || 'unconnected')
      }, {
        key: 'online',
        label: getStatusLabel((smartDevice === null || smartDevice === void 0 ? void 0 : smartDevice.status) || 'unknown'),
        tone: getStatusTone((smartDevice === null || smartDevice === void 0 ? void 0 : smartDevice.status) || 'unknown')
      }],
      connectionStatuses: [{
        key: 'connection',
        label: getStatusLabel(connection.status || 'unconnected'),
        tone: getStatusTone(connection.status || 'unconnected')
      }],
      profiles: (connection.profiles || []).map(function (profile) {
        return {
          key: String(profile.id),
          label: translation(profile.name) || profile.id
        };
      }),
      lastSeen: connection.last_seen ? "".concat(getText('pisell2.saas.device-planning.detail.last-seen')).concat(connection.last_seen) : undefined
    });
  };
  return /*#__PURE__*/React.createElement(PisellModal, {
    open: open,
    width: 760,
    title: /*#__PURE__*/React.createElement("div", {
      className: "device-detail-drawer__preview-title"
    }, /*#__PURE__*/React.createElement("div", {
      className: "device-detail-drawer__preview-icon"
    }, /*#__PURE__*/React.createElement(Icon, {
      type: ((_detailDevice$type = detailDevice.type) === null || _detailDevice$type === void 0 ? void 0 : _detailDevice$type.icon) || 'PrinterOutlined',
      color: DEVICE_ICON_COLOR[detailDevice.type_kind]
    })), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", {
      className: "device-detail-drawer__preview-name"
    }, record.name), /*#__PURE__*/React.createElement("div", {
      className: "device-detail-drawer__preview-type"
    }, record.typeName))),
    closeIcon: /*#__PURE__*/React.createElement(CloseOutlined, null),
    onCancel: onClose,
    okVisible: false,
    cancelText: getText('pisell2.saas.device-planning.preview.close'),
    cancelButtonProps: {
      type: 'default',
      onClick: onClose
    },
    destroyOnClose: true,
    className: "device-detail-drawer__preview-modal",
    bodyStyle: {
      padding: '24px'
    }
  }, /*#__PURE__*/React.createElement(Spin, {
    spinning: loading
  }, /*#__PURE__*/React.createElement(DeviceInfoPanel, {
    record: record,
    getText: getText,
    translation: translation
  }), /*#__PURE__*/React.createElement("div", {
    className: "device-detail-drawer__preview-section"
  }, /*#__PURE__*/React.createElement("div", {
    className: "device-detail-drawer__preview-section-title"
  }, getText('pisell2.saas.device-planning.preview.reported-by-smart')), connections.length ? /*#__PURE__*/React.createElement("div", {
    className: "device-detail-drawer__preview-connection-list"
  }, connections.map(renderConnectionItem)) : /*#__PURE__*/React.createElement(Empty, {
    image: Empty.PRESENTED_IMAGE_SIMPLE,
    description: getText('pisell2.saas.device-planning.drawer.connections.not-connected-smart')
  }))));
};
export default ConnectedDevicePreviewModal;