"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Aura = void 0;
var _react = require("@elevenlabs/react");
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react2 = _interopRequireWildcard(require("react"));
var _Aura = require("./Aura.l10n");
var style = _interopRequireWildcard(require("./Aura.module.css"));
var _Aura2 = require("./Aura.waveform");
var _helpers = require("./helpers");
var _useOpenAiRealtimeSession = require("./hooks/useOpenAiRealtimeSession");
var _Core = require("../../../../Core.constants");
var _helpers2 = 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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
const Aura = _ref => {
  let {
    onCallEnd = () => {}
  } = _ref;
  const conversation = (0, _react.useConversation)();
  const {
    startSession,
    endSession,
    audioAnalyzers
  } = (0, _useOpenAiRealtimeSession.useOpenAiRealtimeSession)();
  const {
    value: {
      assistant = {},
      hotel = {},
      id,
      locale,
      type,
      urlParams: {
        synapse = 'v1'
      } = {}
    } = {}
  } = (0, _dataSources.useStore)();
  const {
    translate
  } = (0, _locale.useLocale)();
  const [context, setContext] = (0, _react2.useState)(null);
  const [isConnecting, setIsConnecting] = (0, _react2.useState)(false);
  const [ready, setReady] = (0, _react2.useState)(false);
  (0, _react2.useEffect)(() => {
    const callback = async () => {
      if (ready) handleCallEnd();
    };
    _dataSources.Event.subscribe(_helpers2.EVENT.SARAI_MESSAGE_SENT, callback);
    return () => {
      _dataSources.Event.unsubscribe(_helpers2.EVENT.SARAI_MESSAGE_SENT, callback);
      if (synapse === 'v2') callback();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [conversation, ready]);
  (0, _react2.useEffect)(() => {
    if (type === _Core.TYPE.CHAIN && !hotel.id) return;
    setContext({
      hotelId: hotel.id
    });
  }, [hotel.id, type]);
  (0, _react2.useEffect)(() => {
    handleCallStart();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [context]);
  const handleCallStart = async () => {
    const {
      name: assistant_name = 'Sarai'
    } = assistant;
    const isChain = type === _Core.TYPE.CHAIN && !hotel.id;
    const chainId = isChain ? id : undefined;
    if (!navigator.mediaDevices || !conversation || !context && !chainId) {
      _dataSources.Event.publish(_helpers2.EVENT.METRICS, {
        id: 'AURA:ERROR'
      });
      return;
    }
    setIsConnecting(true);
    try {
      if (synapse === 'v2') {
        await startSession({
          assistant_name,
          chainId,
          hotelId: context === null || context === void 0 ? void 0 : context.hotelId,
          isChain,
          locale,
          setIsConnecting,
          setReady
        });
        return;
      }
      await navigator.mediaDevices.getUserMedia({
        audio: true
      });
      const sessionConfig = {
        clientTools: {
          open_url: _helpers.toolOpenUrl
        },
        dynamicVariables: _objectSpread({
          assistant_name
        }, chainId ? {
          chain_id: chainId
        } : {
          hotelId: context.hotelId
        }),
        overrides: {
          agent: {
            language: locale.split('-')[0]
          }
        },
        signedUrl: await (0, _helpers.getSignedUrl)(!!chainId),
        onConnect: () => {
          _dataSources.Event.publish(_helpers2.EVENT.METRICS, {
            id: 'AURA:START'
          });
          setIsConnecting(false);
          setReady(true);
        },
        onDisconnect: handleCallEnd,
        onError: error => {
          setIsConnecting(false);
          _dataSources.Event.publish(_helpers2.EVENT.METRICS, {
            id: 'AURA:ERROR',
            error: error === null || error === void 0 ? void 0 : error.message
          });
        }
      };
      await conversation.startSession(sessionConfig);
    } catch (error) {
      setIsConnecting(false);
    }
  };
  const handleCallEnd = () => {
    if (synapse === 'v2') endSession();else conversation.endSession();
    setReady(false);
    onCallEnd();
    _dataSources.Event.publish(_helpers2.EVENT.METRICS, {
      id: 'AURA:CALL_END'
    });
  };
  return !(!context && !(type === _Core.TYPE.CHAIN && !hotel.id)) ? /*#__PURE__*/_react2.default.createElement(_react2.default.Fragment, null, /*#__PURE__*/_react2.default.createElement(_Aura2.Waveform, {
    active: ready,
    conversation: synapse === 'v2' ? audioAnalyzers : conversation
  }), /*#__PURE__*/_react2.default.createElement(_ui.View, {
    className: style.footer
  }, isConnecting && /*#__PURE__*/_react2.default.createElement(_ui.Text, {
    action: true
  }, translate(_Aura.L10N.LABEL_CALLING, {
    name: assistant.name || _Chat.DEFAULT_NAME
  })), /*#__PURE__*/_react2.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__*/_react2.default.createElement(_ui.Icon, {
    value: _helpers2.ICON.HANG_UP
  })))) : null;
};
exports.Aura = Aura;
Aura.displayName = 'Mirai:Core:Chat.Aura';
Aura.propTypes = {
  onCallEnd: _propTypes.default.func
};
//# sourceMappingURL=Aura.js.map