import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { useCallback, useMemo } from 'react';
import FeatureGates from '@atlaskit/feature-gate-js-client';
import { useSmartLinkContext } from '@atlaskit/link-provider';
import { ACTION_RESOLVING, ACTION_UPDATE_METADATA_STATUS, cardAction } from '@atlaskit/linking-common';
import { auth } from '@atlaskit/outbound-auth-flow-client';
import { useAnalyticsEvents } from '../../common/analytics/generated/use-analytics-events';
import { SmartLinkStatus } from '../../constants';
import { AUTH_WINDOW_HEIGHT, AUTH_WINDOW_WIDTH, getWindowOpenFeatures } from '../../utils/window-open-features';
import { startUfoExperience } from '../analytics';
import { getByDefinitionId, getDefinitionId, getExtensionKey, getServices } from '../helpers';
import useInvokeClientAction from '../hooks/use-invoke-client-action';
import useResolve from '../hooks/use-resolve';
export var useSmartCardActions = function useSmartCardActions(id, url) {
  var resolveUrl = useResolve();
  var invokeClientAction = useInvokeClientAction({});
  var _useAnalyticsEvents = useAnalyticsEvents(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  var _useSmartLinkContext = useSmartLinkContext(),
    store = _useSmartLinkContext.store;
  var getState = store.getState,
    dispatch = store.dispatch;
  var getSmartLinkState = useCallback(function () {
    var _getState$url;
    var _ref = (_getState$url = getState()[url]) !== null && _getState$url !== void 0 ? _getState$url : {
        status: SmartLinkStatus.Pending
      },
      details = _ref.details,
      status = _ref.status,
      metadataStatus = _ref.metadataStatus;
    return {
      details: details,
      status: status,
      metadataStatus: metadataStatus
    };
  }, [getState, url]);
  var setMetadataStatus = useCallback(function (metadataStatus) {
    dispatch(cardAction(ACTION_UPDATE_METADATA_STATUS, {
      url: url
    }, undefined, undefined, metadataStatus));
  }, [dispatch, url]);
  var resolve = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var resourceUrl,
      isReloading,
      isMetadataRequest,
      _args = arguments;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          resourceUrl = _args.length > 0 && _args[0] !== undefined ? _args[0] : url;
          isReloading = _args.length > 1 && _args[1] !== undefined ? _args[1] : false;
          isMetadataRequest = _args.length > 2 && _args[2] !== undefined ? _args[2] : false;
          return _context.abrupt("return", resolveUrl(resourceUrl, isReloading, isMetadataRequest, id));
        case 4:
        case "end":
          return _context.stop();
      }
    }, _callee);
  })), [id, resolveUrl, url]);
  var register = useCallback(function () {
    var _getSmartLinkState = getSmartLinkState(),
      details = _getSmartLinkState.details;
    if (!details) {
      dispatch(cardAction(ACTION_RESOLVING, {
        url: url
      }));
      setMetadataStatus('pending');
    }
    return resolve();
  }, [getSmartLinkState, resolve, dispatch, url, setMetadataStatus]);
  var reload = useCallback(function () {
    var _getSmartLinkState2 = getSmartLinkState(),
      details = _getSmartLinkState2.details;
    var definitionId = getDefinitionId(details);
    if (definitionId) {
      getByDefinitionId(definitionId, getState()).map(function (url) {
        return resolve(url, true);
      });
    } else {
      resolve(url, true);
    }
  }, [getSmartLinkState, url, getState, resolve]);
  var loadMetadata = useCallback(function () {
    var _getSmartLinkState3 = getSmartLinkState(),
      metadataStatus = _getSmartLinkState3.metadataStatus;
    //metadataStatus will be undefined for SSR links only
    if (metadataStatus === undefined) {
      setMetadataStatus('pending');
      return resolve(url, false, true);
    }
  }, [getSmartLinkState, resolve, setMetadataStatus, url]);
  var authorize = useCallback(function (appearance) {
    var _getSmartLinkState4 = getSmartLinkState(),
      details = _getSmartLinkState4.details,
      status = _getSmartLinkState4.status;
    var definitionId = getDefinitionId(details);
    var extensionKey = getExtensionKey(details);
    var services = getServices(details);
    // When authentication is triggered, let GAS know!
    if (status === 'unauthorized') {
      fireEvent('ui.button.clicked.connectAccount', {
        display: appearance,
        definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
      });
    }
    if (status === 'forbidden') {
      fireEvent('ui.smartLink.clicked.tryAnotherAccount', {
        display: appearance,
        definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
      });
    }
    if (services.length > 0) {
      fireEvent('screen.consentModal.viewed', {
        definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
      });
      var shouldShowInPopupWindow = status === 'unauthorized' && FeatureGates.getExperimentValue('platform_sl_3p_auth_window_experiment', 'cohort', 'control') === 'test';
      var windowFeatures = shouldShowInPopupWindow ? getWindowOpenFeatures(AUTH_WINDOW_HEIGHT, AUTH_WINDOW_WIDTH) : undefined;
      auth(services[0].url, windowFeatures).then(function () {
        fireEvent('track.applicationAccount.connected', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
        });
        startUfoExperience('smart-link-authenticated', id, {
          extensionKey: extensionKey,
          status: 'success'
        });
        fireEvent('operational.smartLink.connectSucceeded', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
        });
        reload();
      }, function (err) {
        var _err$type;
        startUfoExperience('smart-link-authenticated', id, {
          extensionKey: extensionKey,
          status: err.type
        });
        fireEvent('operational.smartLink.connectFailed', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
          reason: (_err$type = err.type) !== null && _err$type !== void 0 ? _err$type : null
        });
        if (err.type === 'auth_window_closed') {
          fireEvent('ui.consentModal.closed', {
            display: appearance,
            definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
          });
        }
        reload();
      });
    }
  }, [getSmartLinkState, id, reload, fireEvent]);
  var invoke = useCallback( /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(opts, appearance) {
      var key, action, source;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            key = opts.key, action = opts.action;
            source = opts.source || appearance;
            if (!(opts.type === 'client')) {
              _context2.next = 6;
              break;
            }
            _context2.next = 5;
            return invokeClientAction({
              actionFn: opts.action.promise,
              actionType: action.type,
              display: source,
              extensionKey: key
            });
          case 5:
            return _context2.abrupt("return", _context2.sent);
          case 6:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }));
    return function (_x, _x2) {
      return _ref3.apply(this, arguments);
    };
  }(), [invokeClientAction]);
  return useMemo(function () {
    return {
      register: register,
      reload: reload,
      authorize: authorize,
      invoke: invoke,
      loadMetadata: loadMetadata
    };
  }, [register, reload, authorize, invoke, loadMetadata]);
};