import { useEffect, useState } from 'react';
import { useIntl } from 'react-intl';
import { AISummaryService } from './ai-summary-service';
import { AISummariesStore } from './ai-summary-service/store';
/**
 * Stream AI summary for an url.
 * For hook specific to AI summary on as a smart link, please see useAISummaryAction.
 */
export const useAISummary = props => {
  var _AISummariesStore$get;
  const {
    url,
    baseUrl,
    product,
    ari,
    envKey,
    onError,
    onStart,
    onSuccess
  } = props;
  const [state, setState] = useState(((_AISummariesStore$get = AISummariesStore.get(url)) === null || _AISummariesStore$get === void 0 ? void 0 : _AISummariesStore$get.state) || {
    status: 'ready',
    content: ''
  });
  const {
    locale
  } = useIntl();
  useEffect(() => {
    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 && !AISummariesStore.get(url)) {
      AISummariesStore.set(url, new AISummaryService({
        url,
        ari,
        baseUrl,
        product,
        envKey,
        locale,
        onError,
        onStart,
        onSuccess
      }));
    }

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