"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var api_resources_exports = {};
__export(api_resources_exports, {
  getAPIResource: () => getAPIResource,
  getHasAPIResource: () => getHasAPIResource,
  getInitialState: () => getInitialState,
  getSerializedState: () => getSerializedState,
  reducer: () => reducer
});
module.exports = __toCommonJS(api_resources_exports);
var import_api = require("../../api");
var import_deepEqual = __toESM(require("../../utils/deepEqual"));
var import_actions = require("../actions");
function isValidAPIResourceType(resourceType) {
  return resourceType in import_api.APIResourceType;
}
function isLocalizableAPIResourceType(resourceType) {
  return resourceType in import_api.LocalizableAPIResourceType;
}
function compositeId(resourceId, resourceType, locale) {
  return locale != null && isLocalizableAPIResourceType(resourceType) ? `${resourceId}@${locale}` : resourceId;
}
function parseCompositeId(compositeId2) {
  const [resourceId, locale] = compositeId2.split("@");
  return [resourceId, locale ?? null];
}
function getInitialState(serializedState = {
  Swatch: [],
  File: [],
  Typography: [],
  PagePathnameSlice: [],
  GlobalElement: [],
  Table: [],
  Snippet: [],
  Page: [],
  Site: [],
  LocalizedGlobalElement: []
}) {
  return new Map(
    Object.entries(serializedState).map(([resourceType, resources]) => [
      resourceType,
      new Map(
        resources.map(({ id, value, locale }) => [
          compositeId(id, resourceType, locale),
          value
        ])
      )
    ])
  );
}
function getSerializedState(state) {
  const resourceMap = {
    Swatch: [],
    File: [],
    Typography: [],
    PagePathnameSlice: [],
    GlobalElement: [],
    Table: [],
    Snippet: [],
    Page: [],
    Site: [],
    LocalizedGlobalElement: []
  };
  Array.from(state.entries()).forEach(([resourceType, resources]) => {
    const particularResourceMap = [];
    Array.from(resources.entries()).forEach(([compositeId2, value]) => {
      if (value != null) {
        const [id, locale] = parseCompositeId(compositeId2);
        console.assert(
          locale == null || isLocalizableAPIResourceType(resourceType),
          `Unexpected locale for non-localizable resource type ${resourceType}`,
          { id, locale }
        );
        particularResourceMap.push(locale != null ? { id, value, locale } : { id, value });
      }
    });
    resourceMap[resourceType] = particularResourceMap;
  });
  return resourceMap;
}
function getHasAPIResource(state, resourceType, resourceId, locale) {
  return state.get(resourceType)?.has(compositeId(resourceId, resourceType, locale)) ?? false;
}
function getAPIResource(state, resourceType, resourceId, locale) {
  const resource = state.get(resourceType)?.get(compositeId(resourceId, resourceType, locale));
  return resource?.__typename === resourceType ? resource : null;
}
function reducer(state = getInitialState(), action) {
  if (!(0, import_actions.isKnownAction)(action))
    return state;
  switch (action.type) {
    case import_actions.ActionTypes.UPDATE_API_CLIENT_CACHE: {
      const { apiResources } = action.payload;
      return Object.entries(apiResources).reduce((state2, [resourceType, cachedResources]) => {
        const resType = resourceType;
        const cached = cachedResources;
        const existing = state2.get(resType) ?? /* @__PURE__ */ new Map();
        const updated = cached?.reduce((r, { id, value, locale }) => {
          const cid = compositeId(id, resType, locale);
          return r.get(cid) != null ? r : new Map(r).set(cid, value);
        }, existing);
        return updated == null || updated === existing ? state2 : new Map(state2).set(resType, updated);
      }, state);
    }
    case import_actions.ActionTypes.API_RESOURCE_FULFILLED: {
      const { resourceType, resourceId, resource, locale } = action.payload;
      return new Map(state).set(
        resourceType,
        new Map(state.get(resourceType)).set(
          compositeId(resourceId, resourceType, locale),
          resource
        )
      );
    }
    case import_actions.ActionTypes.CHANGE_API_RESOURCE: {
      const { resource, locale } = action.payload;
      const existingApiResource = getAPIResource(state, resource.__typename, resource.id, locale);
      if ((0, import_deepEqual.default)(existingApiResource, resource))
        return state;
      return new Map(state).set(
        resource.__typename,
        new Map(state.get(resource.__typename)).set(
          compositeId(resource.id, resource.__typename, locale),
          resource
        )
      );
    }
    case import_actions.ActionTypes.EVICT_API_RESOURCE: {
      const { id, locale } = action.payload;
      const [resourceType, resourceId] = id.split(":");
      if (!isValidAPIResourceType(resourceType))
        return state;
      const resources = new Map(state.get(resourceType));
      const deleted = resources.delete(compositeId(resourceId, resourceType, locale));
      return deleted ? new Map(state).set(resourceType, resources) : state;
    }
    default:
      return state;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getAPIResource,
  getHasAPIResource,
  getInitialState,
  getSerializedState,
  reducer
});
//# sourceMappingURL=api-resources.js.map