var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __using = (stack, value, async) => {
  if (value != null) {
    if (typeof value !== "object" && typeof value !== "function") __typeError("Object expected");
    var dispose, inner;
    if (async) dispose = value[__knownSymbol("asyncDispose")];
    if (dispose === void 0) {
      dispose = value[__knownSymbol("dispose")];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") __typeError("Object not disposable");
    if (inner) dispose = function() {
      try {
        inner.call(this);
      } catch (e) {
        return Promise.reject(e);
      }
    };
    stack.push([async, dispose, value]);
  } else if (async) {
    stack.push([async]);
  }
  return value;
};
var __callDispose = (stack, error, hasError) => {
  var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
    return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
  };
  var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
  var next = (it) => {
    while (it = stack.pop()) {
      try {
        var result = it[1] && it[1].call(it[2]);
        if (it[0]) return Promise.resolve(result).then(next, (e) => (fail(e), next()));
      } catch (e) {
        fail(e);
      }
    }
    if (hasError) throw error;
  };
  return next();
};
/**
 * @license
 * Copyright 2022-2024 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { NodeActivity } from "#behavior/context/NodeActivity.js";
import { IndexBehavior } from "#behavior/system/index/IndexBehavior.js";
import { PartsBehavior } from "#behavior/system/parts/PartsBehavior.js";
import { Endpoint } from "#endpoint/Endpoint.js";
import { MutableEndpoint } from "#endpoint/index.js";
import {
  Construction,
  Diagnostic,
  DiagnosticSource,
  Environment,
  ImplementationError,
  Logger,
  RuntimeService
} from "#general";
import { RootEndpoint } from "../endpoints/root.js";
import { NodeLifecycle } from "./NodeLifecycle.js";
const logger = Logger.get("Node");
class Node extends Endpoint {
  #environment;
  #runtime;
  constructor(config) {
    const parentEnvironment = config.environment ?? config.owner?.env ?? Environment.default;
    if (config.id === void 0) {
      config.id = `node${parentEnvironment.vars.increment("node.nextFallbackId")}`;
    }
    super(config);
    this.#environment = new Environment(config.id, parentEnvironment);
    this.#environment.set(NodeActivity, new NodeActivity());
    if (this.lifecycle.hasNumber) {
      if (this.number !== 0) {
        throw new ImplementationError("The root endpoint ID must be 0");
      }
    } else {
      this.number = 0;
    }
    this.construction.start();
    this.lifecycle.online.on(() => {
      this.statusUpdate("is online");
    });
    this.lifecycle.offline.on(() => {
      this.statusUpdate("is offline");
    });
  }
  get env() {
    return this.#environment;
  }
  createLifecycle() {
    return new NodeLifecycle(this);
  }
  /**
   * Bring the node online.
   */
  async start() {
    this.env.runtime.add(this);
    try {
      await this.construction.ready;
      if (this.#runtime) {
        return;
      }
      this.statusUpdate("going online");
      this.#runtime = this.createRuntime();
      this.#runtime.construction.start();
      await this.#runtime.construction.ready;
    } catch (e) {
      this.env.runtime.delete(this);
      throw e;
    }
  }
  /**
   * @deprecated use {@link start}
   */
  async bringOnline() {
    return this.start();
  }
  /**
   * Run the node in standalone mode.  Returns when the node is closed.
   */
  async run() {
    await this.start();
    await this.construction.closed;
  }
  /**
   * Take the node offline but leave state and structure intact.  Happens automatically on close.
   *
   * Once the node is offline you may use {@link start} to bring the node online again.
   */
  async cancel() {
    if (!this.#runtime) {
      return;
    }
    this.statusUpdate("going offline");
    await this.#runtime?.close();
    this.#runtime = void 0;
  }
  async close() {
    if (this.#runtime) {
      await this.cancel();
    }
    await super.close();
  }
  get [RuntimeService.label]() {
    return ["Runtime for", Diagnostic.strong(this.toString())];
  }
  get [Diagnostic.value]() {
    var _stack = [];
    try {
      const nodeActivity = this.#environment.get(NodeActivity);
      const _activity = __using(_stack, nodeActivity.begin("diagnostics"));
      return Diagnostic.node("\u{1F9E9}", this.id, {
        children: [
          Diagnostic.strong("Structure"),
          Diagnostic.list([super[Diagnostic.value]]),
          Diagnostic.strong("Activity"),
          nodeActivity[Diagnostic.value]
        ]
      });
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  get lifecycle() {
    return super.lifecycle;
  }
  statusUpdate(message) {
    logger.notice(Diagnostic.strong(this.toString()), message);
  }
  async [Construction.destruct]() {
    await this.cancel();
    await super[Construction.destruct]();
    DiagnosticSource.delete(this);
  }
}
((Node2) => {
  function nodeConfigFor(defaultType, configuration, options) {
    if (!options) {
      options = {};
    }
    if (configuration === void 0) {
      return {
        type: defaultType,
        ...options
      };
    }
    if (configuration.deviceType !== void 0) {
      return {
        type: configuration,
        ...options
      };
    }
    return {
      type: defaultType,
      ...configuration
    };
  }
  Node2.nodeConfigFor = nodeConfigFor;
  Node2.CommonRootEndpoint = MutableEndpoint({
    name: RootEndpoint.name,
    deviceType: RootEndpoint.deviceType,
    deviceRevision: RootEndpoint.deviceRevision,
    deviceClass: RootEndpoint.deviceClass,
    requirements: RootEndpoint.requirements,
    behaviors: {
      parts: PartsBehavior,
      index: IndexBehavior
    }
  });
})(Node || (Node = {}));
export {
  Node
};
//# sourceMappingURL=Node.js.map
