/**
 * @license
 * Copyright 2022-2025 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { RootSupervisor } from "#behavior/supervision/RootSupervisor.js";
import { InternalError, NotImplementedError } from "#general";
import { Metatype } from "#model";
import { StatusResponse } from "@matter/types";
import { ApiResource } from "../ApiResource.js";
import { Envelope } from "../Envelope.js";
class PropertyResource extends ApiResource {
  id;
  supervisor;
  dataModelPath;
  get valueKind() {
    if (this.schema.tag === "attribute") {
      return "attribute";
    }
    return "field";
  }
  constructor(parent, id, supervisor, path) {
    super(parent);
    this.id = id;
    this.supervisor = supervisor;
    this.dataModelPath = path;
  }
  get schema() {
    return this.supervisor.schema;
  }
  get value() {
    return this.parent?.value?.[this.id];
  }
  write(request) {
    const requestEnv = new Envelope({ supervisor: this.supervisor, ...request });
    requestEnv.validate();
    this.#target[this.id] = requestEnv.js;
  }
  patch(request) {
    request = new Envelope({ supervisor: this.supervisor, ...request });
    request.validate();
    this.#targetSupervisor.patch({ [this.id]: request.js }, this.#target, this.dataModelPath);
  }
  add(request) {
    const struct = this.#target;
    if (!Array.isArray(struct)) {
      throw new NotImplementedError();
    }
    request = new Envelope({ supervisor: this.supervisor, ...request });
    struct.push(request.js);
  }
  delete() {
    const struct = this.#target;
    if (Array.isArray(struct)) {
      struct.splice(this.id, 1);
    } else {
      this.#target[this.id] = void 0;
    }
  }
  async childFor(id) {
    let mySchema;
    switch (this.schema.effectiveMetatype) {
      case Metatype.object:
        mySchema = this.schema.conformant.properties.for(id);
        break;
      case Metatype.array:
        if (!id.match(/^\d+$/)) {
          mySchema = void 0;
        } else {
          mySchema = this.schema.conformant.properties.for("entry");
        }
        break;
      default:
        throw new NotImplementedError();
    }
    if (!mySchema) {
      throw new StatusResponse.NotFoundError();
    }
    const myCollection = this.#target[this.id];
    if (!myCollection) {
      return;
    }
    return new PropertyResource(this, id, this.supervisorFor(mySchema), this.dataModelPath.at(id));
  }
  get #target() {
    const collection = this.parent?.value;
    if (!collection || typeof collection !== "object") {
      throw new InternalError("Value of property item has no collection");
    }
    return collection;
  }
  get #targetSupervisor() {
    const supervisor = RootSupervisor.for(this.parent?.schema);
    if (!supervisor) {
      throw new InternalError("No supervisor for parent collection");
    }
    return supervisor;
  }
}
export {
  PropertyResource
};
//# sourceMappingURL=PropertyResource.js.map
