"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _reduxBundler = require("redux-bundler");

var _getEventSourceManager = require("./get-event-source-manager");

//@ts-check

/** @typedef {'CreateResource' | 'UpdateResource' | 'DeleteResource'} FHIRActionType */

/**
 * @param {{
 *   apiUrl: string
 *   orgIdSelector: string
 *   eventFilter?: any
 *   logger?: any
 *   customHandlers?: any
 *   eventSourceConstructor?: any
 * }} Opts
 */
var _default = ({
  apiUrl,
  eventFilter,
  customHandlers,
  orgIdSelector,
  logger,
  eventSourceConstructor
}) => (0, _getEventSourceManager.getEventSourceManagerBundle)({
  name: 'orgEventSource',
  actionBaseName: 'ORG_EVENT_SOURCE',
  eventSourceConstructor,
  dataActionCreatorName: 'doReceiveOrgFhirEvents',
  activeIdsSelectorName: 'selectOrgIdsToBeSubscribedTo',
  logger,
  buildUrl: (orgId, store) => {
    // we pass token explicitly for localhost to
    // enable hitting dev API without needing to have
    // valid token cookie.
    const addOn = store.selectHostname() === 'localhost' ? "?token=".concat(store.selectAuthToken()) : '';
    return "".concat(apiUrl, "/fhir-sse/org/").concat(orgId).concat(addOn);
  },
  doReceiveOrgFhirEvents: ({
    data
  }) => ({
    store
  }) => {
    const {
      action,
      orgId,
      resourceId,
      resourceType
    } = data;
    const resourceReference = "".concat(resourceType, "/").concat(resourceId);

    if (eventFilter && !eventFilter({
      action,
      resourceType,
      resourceReference,
      store,
      orgId
    })) {
      return;
    }

    const customHandler = customHandlers && customHandlers[resourceType] && customHandlers[resourceType][action];

    if (customHandler) {
      customHandler(store, {
        resourceId,
        orgId
      });
      return;
    } // we always fetch newly created resources
    // there's no way to know whether we need them


    if (action === 'CreateResource') {
      store.doFetchFhirResource(resourceReference, orgId);
      return;
    } // For update and delete we don't know if we have it
    // we only do something if we do


    if (action === 'UpdateResource') {
      const found = store.utilFindFhirResourceById(resourceId);

      if (found) {
        store.doFetchFhirResource(resourceReference, orgId);
      }

      return;
    }

    if (action === 'DeleteResource') {
      const found = store.utilFindFhirResourceById(resourceId);

      if (found) {
        store.doRemoveFhirResource({
          id: resourceId,
          orgId,
          resourceType
        });
      }

      return;
    }
  },
  selectOrgIdsToBeSubscribedTo: (0, _reduxBundler.createSelector)('selectIsFullyAuthenticated', orgIdSelector, (fullyAuthed, orgIds) => {
    if (!fullyAuthed || !orgIds) {
      return [];
    }

    return orgIds;
  })
});

exports.default = _default;