"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Aura = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _Aura = require("./Aura.l10n");
var style = _interopRequireWildcard(require("./Aura.module.css"));
var _Aura2 = require("./Aura.waveform");
var _useOpenAiRealtimeSession = require("./hooks/useOpenAiRealtimeSession");
var _useXaiRealtimeSession = require("./hooks/useXaiRealtimeSession");
var _Core = require("../../../../Core.constants");
var _helpers = require("../../../helpers");
var _Chat = require("../../Chat.constants");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
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(r) { if (Array.isArray(r)) return r; }
const VOICE_MODEL_XAI = 'xai';
const Aura = _ref => {
  var _urlParams$voiceMode;
  let hotelId = _ref.hotelId,
    _ref$onCallEnd = _ref.onCallEnd,
    onCallEnd = _ref$onCallEnd === void 0 ? () => {} : _ref$onCallEnd,
    settings = _ref.settings;
  const openAiSession = (0, _useOpenAiRealtimeSession.useOpenAiRealtimeSession)();
  const xaiSession = (0, _useXaiRealtimeSession.useXaiRealtimeSession)();
  const _useStore = (0, _dataSources.useStore)(),
    _useStore$value = _useStore.value,
    _useStore$value2 = _useStore$value === void 0 ? {} : _useStore$value,
    id = _useStore$value2.id,
    locale = _useStore$value2.locale,
    type = _useStore$value2.type,
    _useStore$value2$urlP = _useStore$value2.urlParams,
    urlParams = _useStore$value2$urlP === void 0 ? {} : _useStore$value2$urlP;
  const useXai = ((_urlParams$voiceMode = urlParams['voice-model']) === null || _urlParams$voiceMode === void 0 ? void 0 : _urlParams$voiceMode.toLowerCase()) === VOICE_MODEL_XAI;
  const _ref2 = useXai ? xaiSession : openAiSession,
    startSession = _ref2.startSession,
    endSession = _ref2.endSession,
    audioAnalyzers = _ref2.audioAnalyzers;
  const _useLocale = (0, _locale.useLocale)(),
    translate = _useLocale.translate;
  const _ref3 = settings || {},
    _ref3$ai = _ref3.ai,
    _ref3$ai2 = _ref3$ai === void 0 ? {} : _ref3$ai,
    _ref3$ai2$name = _ref3$ai2.name,
    assistantName = _ref3$ai2$name === void 0 ? _Chat.DEFAULT_NAME : _ref3$ai2$name;
  const _useState = (0, _react.useState)(null),
    _useState2 = _slicedToArray(_useState, 2),
    context = _useState2[0],
    setContext = _useState2[1];
  const _useState3 = (0, _react.useState)(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isConnecting = _useState4[0],
    setIsConnecting = _useState4[1];
  const _useState5 = (0, _react.useState)(false),
    _useState6 = _slicedToArray(_useState5, 2),
    ready = _useState6[0],
    setReady = _useState6[1];
  (0, _react.useEffect)(() => {
    if (type === _Core.TYPE.CHAIN && !hotelId) return;
    setContext({
      hotelId
    });
  }, [hotelId, type]);
  const handleCallEnd = (0, _react.useCallback)(() => {
    endSession();
    setReady(false);
    onCallEnd();
    _dataSources.Event.publish(_helpers.EVENT.METRICS, {
      id: _helpers.METRICS_EVENTS.AURA_CALL_END
    });
  }, [endSession, onCallEnd]);
  (0, _react.useEffect)(() => {
    handleCallStart();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [context]);
  (0, _react.useEffect)(() => {
    const callback = () => {
      if (ready) handleCallEnd();
    };
    _dataSources.Event.subscribe(_helpers.EVENT.CHAT_CLOSE, callback);
    return () => {
      _dataSources.Event.unsubscribe(_helpers.EVENT.CHAT_CLOSE, callback);
    };
  }, [handleCallEnd, ready]);
  const handleCallStart = async () => {
    const isChain = type === _Core.TYPE.CHAIN && !hotelId;
    const chainId = isChain ? id : undefined;
    if (!navigator.mediaDevices || !context && !chainId) {
      _dataSources.Event.publish(_helpers.EVENT.METRICS, {
        id: _helpers.METRICS_EVENTS.AURA_ERROR
      });
      return;
    }
    setIsConnecting(true);
    try {
      await startSession({
        assistant_name: assistantName,
        chainId,
        hotelId,
        isChain,
        locale,
        setIsConnecting,
        setReady
      });
    } catch (error) {
      setIsConnecting(false);
    }
  };
  return !(!context && !(type === _Core.TYPE.CHAIN && !hotelId)) ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_Aura2.Waveform, {
    active: ready,
    conversation: audioAnalyzers
  }), /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.footer
  }, isConnecting && /*#__PURE__*/_react.default.createElement(_ui.Text, {
    action: true
  }, translate(_Aura.L10N.LABEL_CALLING, {
    name: assistantName
  })), /*#__PURE__*/_react.default.createElement(_ui.Button, {
    busy: isConnecting,
    rounded: true,
    squared: true,
    large: true,
    tooltip: translate(_Aura.L10N.LABEL_HANG_UP),
    onPress: handleCallEnd,
    className: (0, _ui.styles)(style.button, ready && style.ready)
  }, /*#__PURE__*/_react.default.createElement(_ui.Icon, {
    value: _helpers.ICON.HANG_UP
  })))) : null;
};
exports.Aura = Aura;
Aura.displayName = 'Mirai:Core:Chat.Aura';
Aura.propTypes = {
  hotelId: _propTypes.default.string,
  onCallEnd: _propTypes.default.func,
  settings: _propTypes.default.shape({
    ai: _propTypes.default.shape({
      name: _propTypes.default.string
    })
  })
};
//# sourceMappingURL=Aura.js.map