"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useWorkspace = useWorkspace;
function _react() {
  const data = require("react");
  _react = function () {
    return data;
  };
  return data;
}
function _component() {
  const data = require("@teambit/component");
  _component = function () {
    return data;
  };
  return data;
}
function _latest() {
  const data = _interopRequireDefault(require("@react-hook/latest"));
  _latest = 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 _client() {
  const data = require("@apollo/client");
  _client = function () {
    return data;
  };
  return data;
}
function _componentId() {
  const data = require("@teambit/component-id");
  _componentId = function () {
    return data;
  };
  return data;
}
function _workspaceModel() {
  const data = require("./workspace-model");
  _workspaceModel = function () {
    return data;
  };
  return data;
}
const _excluded = ["data", "subscribeToMore"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
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); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; }
const wcComponentFields = (0, _client().gql)`
  fragment wcComponentFields on Component {
    id {
      name
      version
      scope
    }
    aspects(include: ["teambit.preview/preview", "teambit.envs/envs"]) {
      # 'id' property in gql refers to a *global* identifier and used for caching.
      # this makes aspect data cache under the same key, even when they are under different components.
      # renaming the property fixes that.
      aspectId: id
      data
    }
    compositions {
      identifier
    }
    description
    issuesCount
    status {
      isOutdated
      isNew
      isInScope
      isStaged
      modifyInfo {
        hasModifiedFiles
        hasModifiedDependencies
      }
      isDeleted
    }
    buildStatus
    preview {
      includesEnvTemplate
      legacyHeader
      isScaling
      skipIncludes
    }
    deprecation {
      isDeprecate
      newId
    }
    server {
      env
      url
    }
    env {
      id
      icon
    }
  }
`;
const WORKSPACE = (0, _client().gql)`
  query workspace {
    workspace {
      name
      path
      icon
      components {
        ...wcComponentFields
      }
    }
  }
  ${wcComponentFields}
`;
const COMPONENT_SUBSCRIPTION_ADDED = (0, _client().gql)`
  subscription OnComponentAdded {
    componentAdded {
      component {
        ...wcComponentFields
      }
    }
  }
  ${wcComponentFields}
`;
const COMPONENT_SUBSCRIPTION_CHANGED = (0, _client().gql)`
  subscription OnComponentChanged {
    componentChanged {
      component {
        ...wcComponentFields
      }
    }
  }
  ${wcComponentFields}
`;
const COMPONENT_SUBSCRIPTION_REMOVED = (0, _client().gql)`
  subscription OnComponentRemoved {
    componentRemoved {
      componentIds {
        name
        version
        scope
      }
    }
  }
`;
function useWorkspace(options = {}) {
  const _useDataQuery = (0, _uiFoundationUiHooks().useDataQuery)(WORKSPACE),
    {
      data,
      subscribeToMore
    } = _useDataQuery,
    rest = _objectWithoutProperties(_useDataQuery, _excluded);
  const optionsRef = (0, _latest().default)(options);
  (0, _react().useEffect)(() => {
    const unSubCompAddition = subscribeToMore({
      document: COMPONENT_SUBSCRIPTION_ADDED,
      updateQuery: (prev, {
        subscriptionData
      }) => {
        const update = subscriptionData.data;
        const addedComponent = update?.componentAdded?.component;
        if (!addedComponent) return prev;
        const componentExists = prev.workspace.components.find(component => _componentId().ComponentID.isEqualObj(component.id, addedComponent.id, {
          ignoreVersion: true
        }));
        if (componentExists) return prev;

        // side effect - trigger observers
        setTimeout(() => optionsRef.current.onComponentAdded?.([_component().ComponentModel.from(addedComponent)]));
        return _objectSpread(_objectSpread({}, prev), {}, {
          workspace: _objectSpread(_objectSpread({}, prev.workspace), {}, {
            components: [...prev.workspace.components, addedComponent]
          })
        });
      }
    });
    const unSubCompChange = subscribeToMore({
      document: COMPONENT_SUBSCRIPTION_CHANGED,
      updateQuery: (prev, {
        subscriptionData
      }) => {
        const update = subscriptionData.data;
        if (!update) return prev;
        const updatedComponent = update.componentChanged.component;
        // side effect - trigger observers
        setTimeout(() => optionsRef.current.onComponentUpdated?.([_component().ComponentModel.from(updatedComponent)]));
        return _objectSpread(_objectSpread({}, prev), {}, {
          workspace: _objectSpread(_objectSpread({}, prev.workspace), {}, {
            components: prev.workspace.components.map(component => component.id.name === updatedComponent.id.name ? updatedComponent : component)
          })
        });
      }
    });
    const unSubCompRemoved = subscribeToMore({
      document: COMPONENT_SUBSCRIPTION_REMOVED,
      updateQuery: (prev, {
        subscriptionData
      }) => {
        const idsToRemove = subscriptionData.data?.componentRemoved?.componentIds;
        if (!idsToRemove || idsToRemove.length === 0) return prev;

        // side effect - trigger observers
        setTimeout(() => optionsRef.current.onComponentRemoved?.(idsToRemove.map(id => _componentId().ComponentID.fromObject(id))));
        return _objectSpread(_objectSpread({}, prev), {}, {
          workspace: _objectSpread(_objectSpread({}, prev.workspace), {}, {
            components: prev.workspace.components.filter(component => idsToRemove.every(id => !_componentId().ComponentID.isEqualObj(id, component.id)))
          })
        });
      }
    });

    // TODO - sub to component removal

    return () => {
      unSubCompAddition();
      unSubCompChange();
      unSubCompRemoved();
    };
  }, [optionsRef]);
  const workspace = (0, _react().useMemo)(() => {
    return data?.workspace ? _workspaceModel().Workspace.from(data?.workspace) : undefined;
  }, [data?.workspace]);
  return _objectSpread({
    workspace,
    subscribeToMore
  }, rest);
}

//# sourceMappingURL=use-workspace.js.map