// src/Component.ts
import { mapObject, uuid } from "@mud-classic/utils";

// src/constants.ts
var OptionalTypes = [
  10 /* OptionalEntity */,
  12 /* OptionalEntityArray */,
  2 /* OptionalNumber */,
  6 /* OptionalNumberArray */,
  4 /* OptionalString */,
  8 /* OptionalStringArray */,
  14 /* OptionalT */
];

// src/Component.ts
function getComponentValue(component, entity) {
  const value = {};
  const schemaKeys = Object.keys(component.schema);
  for (const key of schemaKeys) {
    const val = component.values[key].get(entity);
    if (val === void 0 && !OptionalTypes.includes(component.schema[key]))
      return void 0;
    value[key] = val;
  }
  return value;
}
function getComponentEntities(component) {
  return component.entities();
}

// src/Indexer.ts
function createIndexer(component) {
  const valueToEntities = /* @__PURE__ */ new Map();
  function getEntitiesWithValue(value) {
    const entities = valueToEntities.get(getValueKey(value));
    return entities ? /* @__PURE__ */ new Set([...entities]) : /* @__PURE__ */ new Set();
  }
  function getValueKey(value) {
    return Object.values(value).join("/");
  }
  function add(entity, value) {
    if (!value)
      return;
    const valueKey = getValueKey(value);
    let entitiesWithValue = valueToEntities.get(valueKey);
    if (!entitiesWithValue) {
      entitiesWithValue = /* @__PURE__ */ new Set();
      valueToEntities.set(valueKey, entitiesWithValue);
    }
    entitiesWithValue.add(entity);
  }
  function remove(entity, value) {
    if (!value)
      return;
    const valueKey = getValueKey(value);
    const entitiesWithValue = valueToEntities.get(valueKey);
    if (!entitiesWithValue)
      return;
    entitiesWithValue.delete(entity);
  }
  for (const entity of getComponentEntities(component)) {
    const value = getComponentValue(component, entity);
    add(entity, value);
  }
  const subscription = component.update$.subscribe(({ entity, value }) => {
    remove(entity, value[1]);
    add(entity, value[0]);
  });
  component.world.registerDisposer(() => subscription == null ? void 0 : subscription.unsubscribe());
  return { ...component, getEntitiesWithValue };
}
export {
  createIndexer
};
//# sourceMappingURL=Indexer.js.map