"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useComponentQuery = useComponentQuery;
function _react() {
  const data = require("react");
  _react = function () {
    return data;
  };
  return data;
}
function _uiFoundationUiHooks() {
  const data = require("@teambit/ui-foundation.ui.hooks.use-data-query");
  _uiFoundationUiHooks = function () {
    return data;
  };
  return data;
}
function _componentId() {
  const data = require("@teambit/component-id");
  _componentId = function () {
    return data;
  };
  return data;
}
function _componentDescriptor() {
  const data = require("@teambit/component-descriptor");
  _componentDescriptor = function () {
    return data;
  };
  return data;
}
function _componentModel() {
  const data = require("./component-model");
  _componentModel = function () {
    return data;
  };
  return data;
}
function _useComponent() {
  const data = require("./use-component.fragments");
  _useComponent = function () {
    return data;
  };
  return data;
}
function _useComponentLogs() {
  const data = require("./use-component-logs");
  _useComponentLogs = function () {
    return data;
  };
  return data;
}
function _componentError() {
  const data = require("./component-error");
  _componentError = function () {
    return data;
  };
  return data;
}
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/** provides data to component ui page, making sure both variables and return value are safely typed and memoized */
function useComponentQuery(componentId, host, filters, skip) {
  const idRef = (0, _react().useRef)(componentId);
  idRef.current = componentId;
  const variables = {
    id: componentId,
    extensionId: host
  };
  const {
    data,
    error,
    loading,
    subscribeToMore
  } = (0, _uiFoundationUiHooks().useDataQuery)(_useComponent().GET_COMPONENT, {
    variables,
    skip,
    errorPolicy: 'all'
  });
  const {
    loading: loadingLogs,
    componentLogs: {
      logs
    } = {}
  } = (0, _useComponentLogs().useComponentLogs)(componentId, host, filters, skip);
  const rawComponent = data?.getHost?.get;
  (0, _react().useEffect)(() => {
    // @TODO @Kutner fix subscription for scope
    if (host !== 'teambit.workspace/workspace') {
      return () => {};
    }
    const unsubAddition = subscribeToMore({
      document: _useComponent().SUB_SUBSCRIPTION_ADDED,
      updateQuery: (prev, {
        subscriptionData
      }) => {
        const prevComponent = prev?.getHost?.get;
        const addedComponent = subscriptionData?.data?.componentAdded?.component;
        if (!addedComponent || prevComponent) return prev;
        if (idRef.current === addedComponent.id.name) {
          return _objectSpread(_objectSpread({}, prev), {}, {
            getHost: _objectSpread(_objectSpread({}, prev.getHost), {}, {
              get: addedComponent
            })
          });
        }
        return prev;
      }
    });
    const unsubChanges = subscribeToMore({
      document: _useComponent().SUB_COMPONENT_CHANGED,
      updateQuery: (prev, {
        subscriptionData
      }) => {
        if (!subscriptionData.data) return prev;
        const prevComponent = prev?.getHost?.get;
        const updatedComponent = subscriptionData?.data?.componentChanged?.component;
        const isUpdated = updatedComponent && _componentId().ComponentID.isEqualObj(prevComponent?.id, updatedComponent?.id);
        if (isUpdated) {
          return _objectSpread(_objectSpread({}, prev), {}, {
            getHost: _objectSpread(_objectSpread({}, prev.getHost), {}, {
              get: updatedComponent
            })
          });
        }
        return prev;
      }
    });
    const unsubRemoval = subscribeToMore({
      document: _useComponent().SUB_COMPONENT_REMOVED,
      updateQuery: (prev, {
        subscriptionData
      }) => {
        if (!subscriptionData.data) return prev;
        const prevComponent = prev?.getHost?.get;
        const removedIds = subscriptionData?.data?.componentRemoved?.componentIds;
        if (!prevComponent || !removedIds?.length) return prev;
        const isRemoved = removedIds.some(removedId => _componentId().ComponentID.isEqualObj(removedId, prevComponent.id));
        if (isRemoved) {
          return _objectSpread(_objectSpread({}, prev), {}, {
            getHost: _objectSpread(_objectSpread({}, prev.getHost), {}, {
              get: null
            })
          });
        }
        return prev;
      }
    });
    return () => {
      unsubChanges();
      unsubAddition();
      unsubRemoval();
    };
  }, []);
  const idDepKey = rawComponent?.id ? `${rawComponent?.id?.scope}/${rawComponent?.id?.name}@${rawComponent?.id?.version}}` : undefined;
  const id = (0, _react().useMemo)(() => rawComponent ? _componentId().ComponentID.fromObject(rawComponent.id) : undefined, [idDepKey]);
  const componentError = error && !data ? new (_componentError().ComponentError)(500, error.message) : !rawComponent && !loading && new (_componentError().ComponentError)(404) || undefined;
  const component = (0, _react().useMemo)(() => rawComponent ? _componentModel().ComponentModel.from(_objectSpread(_objectSpread({}, rawComponent), {}, {
    host,
    logs
  })) : undefined, [id?.toString(), logs]);
  const componentDescriptor = (0, _react().useMemo)(() => {
    const aspectList = {
      entries: rawComponent?.aspects.map(aspectObject => {
        return _objectSpread(_objectSpread({}, aspectObject), {}, {
          aspectId: aspectObject.id,
          aspectData: aspectObject.data
        });
      })
    };
    return id ? _componentDescriptor().ComponentDescriptor.fromObject({
      id: id.toString(),
      aspectList
    }) : undefined;
  }, [id?.toString()]);
  return (0, _react().useMemo)(() => {
    return {
      componentDescriptor,
      component,
      componentLogs: {
        loading: loadingLogs,
        logs
      },
      error: componentError || undefined,
      loading
    };
  }, [host, component, componentDescriptor, componentError]);
}

//# sourceMappingURL=use-component-query.js.map