/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { ClusterModel, ValueModel } from "@matter/model";
import { Internal } from "./Internal.js";
function NameResolver(supervisor, model, name) {
  if (model === void 0) {
    return;
  }
  if (name.includes(".")) {
    return resolveQualifiedName(supervisor, model, name);
  }
  if (model === supervisor.schema || model.id !== void 0 && supervisor.schema.tag === model.tag && supervisor.schema.id === model.id) {
    if (!supervisor.memberNames.has(name)) {
      return;
    }
    return createDirectResolver(findMemberId(supervisor.schema, name));
  }
  if (!(model instanceof ValueModel) || model.effectiveMetatype !== "object") {
    return createIndirectResolver();
  }
  const member = supervisor.membersOf(model).find((model2) => model2.propertyName === name);
  if (member) {
    return createDirectResolver(member.id);
  }
  return createIndirectResolver();
  function createDirectResolver(id) {
    if (id === void 0) {
      return (val) => val?.[name];
    }
    return (val) => {
      const struct = val;
      if (struct === void 0 || struct === null) {
        return void 0;
      }
      if (id in struct) {
        return struct[id];
      }
      return struct[name];
    };
  }
  function findMemberId(schema, name2) {
    return supervisor.membersOf(schema).find((model2) => model2.propertyName === name2)?.id;
  }
  function createIndirectResolver() {
    const parentSchema = model.parent;
    if (!(parentSchema instanceof ValueModel) && !(parentSchema instanceof ClusterModel)) {
      return;
    }
    const parentReader = NameResolver(supervisor, parentSchema, name);
    if (!parentReader) {
      return;
    }
    return (val) => {
      const parent = val?.[Internal.reference]?.parent?.owner;
      if (parent) {
        return parentReader(parent);
      }
    };
  }
}
function resolveQualifiedName(supervisor, model, name) {
  const segments = name.split(".");
  const baseResolver = NameResolver(supervisor, model, segments[0]);
  if (!baseResolver) {
    return;
  }
  const rest = segments.slice(1);
  return (val) => {
    let result = baseResolver(val);
    for (const segment of rest) {
      if (result === void 0 || result === null) {
        return void 0;
      }
      result = result?.[segment];
    }
    return result;
  };
}
export {
  NameResolver
};
//# sourceMappingURL=NameResolver.js.map
