"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useAISummary = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = require("react");
var _reactIntl = require("react-intl");
var _aiSummaryService = require("./ai-summary-service");
var _store = require("./ai-summary-service/store");
/**
 * Stream AI summary for an url.
 * For hook specific to AI summary on as a smart link, please see useAISummaryAction.
 */
var useAISummary = exports.useAISummary = function useAISummary(props) {
  var _AISummariesStore$get;
  var url = props.url,
    baseUrl = props.baseUrl,
    product = props.product,
    ari = props.ari,
    envKey = props.envKey,
    onError = props.onError,
    onStart = props.onStart,
    onSuccess = props.onSuccess;
  var _useState = (0, _react.useState)(((_AISummariesStore$get = _store.AISummariesStore.get(url)) === null || _AISummariesStore$get === void 0 ? void 0 : _AISummariesStore$get.state) || {
      status: 'ready',
      content: ''
    }),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    state = _useState2[0],
    setState = _useState2[1];
  var _useIntl = (0, _reactIntl.useIntl)(),
    locale = _useIntl.locale;
  (0, _react.useEffect)(function () {
    var _AISummariesStore$get2;
    //do not create a service for the empty URL string when the link data is not yet available,
    //or the service has already been created and cached.
    if (url && !_store.AISummariesStore.get(url)) {
      _store.AISummariesStore.set(url, new _aiSummaryService.AISummaryService({
        url: url,
        ari: ari,
        baseUrl: baseUrl,
        product: product,
        envKey: envKey,
        locale: locale,
        onError: onError,
        onStart: onStart,
        onSuccess: onSuccess
      }));
    }

    //returns function that calls unsubscribe method
    return (_AISummariesStore$get2 = _store.AISummariesStore.get(url)) === null || _AISummariesStore$get2 === void 0 ? void 0 : _AISummariesStore$get2.subscribe(setState);
  }, [url, baseUrl, onError, onStart, onSuccess, product, ari, envKey, locale]);
  var summariseUrl = function summariseUrl() {
    var _AISummariesStore$get3;
    return (_AISummariesStore$get3 = _store.AISummariesStore.get(url)) === null || _AISummariesStore$get3 === void 0 ? void 0 : _AISummariesStore$get3.summariseUrl();
  };
  return {
    summariseUrl: summariseUrl,
    state: state
  };
};