import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { useCallback } from 'react';
import { isEntityPresent } from '@atlaskit/link-extractors';
import { useSmartLinkContext } from '@atlaskit/link-provider';
import { SmartLinkStatus } from '../../../constants';
import { addMetadataToExperience } from '../../analytics';
import useResponse from '../use-response';
var useResolve = function useResolve() {
  // Request JSON-LD data for the card from ORS, if it has extended
  // its cache lifespan OR there is no data for it currently. Once the data
  // has come back asynchronously, call the useResponse callback to
  // dispatch the resolved action for the card.
  var _useSmartLinkContext = useSmartLinkContext(),
    store = _useSmartLinkContext.store,
    connections = _useSmartLinkContext.connections;
  var getState = store.getState;
  var _useResponse = useResponse(),
    handleResolvedLinkResponse = _useResponse.handleResolvedLinkResponse,
    handleResolvedLinkError = _useResponse.handleResolvedLinkError;
  return useCallback( /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(url) {
      var isReloading,
        isMetadataRequest,
        id,
        _ref2,
        details,
        hasData,
        _args = arguments;
      return _regeneratorRuntime.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            isReloading = _args.length > 1 && _args[1] !== undefined ? _args[1] : false;
            isMetadataRequest = _args.length > 2 && _args[2] !== undefined ? _args[2] : false;
            id = _args.length > 3 && _args[3] !== undefined ? _args[3] : '';
            _ref2 = getState()[url] || {
              status: SmartLinkStatus.Pending,
              details: undefined
            }, details = _ref2.details;
            hasData = !!(details && details.data || isEntityPresent(details));
            if (!(isReloading || !hasData || isMetadataRequest)) {
              _context.next = 1;
              break;
            }
            return _context.abrupt("return", connections.client.fetchData(url, isReloading).then(function (response) {
              return handleResolvedLinkResponse(url, response, isReloading, isMetadataRequest);
            }).catch(function (error) {
              return handleResolvedLinkError(url, error, undefined, isMetadataRequest);
            }));
          case 1:
            addMetadataToExperience('smart-link-rendered', id, {
              cached: true
            });
          case 2:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref.apply(this, arguments);
    };
  }(), [connections.client, getState, handleResolvedLinkError, handleResolvedLinkResponse]);
};
export default useResolve;