/**
 * @license
 * Copyright 2022-2025 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { EventEmitter, Observable } from "#general";
import { SessionManager } from "#protocol";
import { Behavior } from "../../Behavior.js";
class SessionsBehavior extends Behavior {
  static id = "sessions";
  initialize() {
    const env = this.env;
    if (env.has(SessionManager)) {
      this.#enterOnlineMode(env.get(SessionManager));
    }
    this.reactTo(this.endpoint.lifecycle.offline, this.#enterOfflineMode);
  }
  #convertToExposedSession(session) {
    return {
      name: session.via,
      nodeId: session.nodeId,
      peerNodeId: session.peerNodeId,
      fabric: session.fabric?.externalInformation,
      isPeerActive: session.isPeerActive,
      lastInteractionTimestamp: session.timestamp,
      lastActiveTimestamp: session.activeTimestamp,
      numberOfActiveSubscriptions: session.subscriptions.size
    };
  }
  #enterOnlineMode(sessions) {
    this.reactTo(sessions.sessions.added, this.#sessionOpened);
    this.reactTo(sessions.sessions.deleted, this.#sessionClosed);
    this.reactTo(sessions.subscriptionsChanged, this.#subscriptionsChanged, { lock: true });
  }
  #sessionOpened(session) {
    if (session.isPase) {
      return;
    }
    const exposedSession = this.#convertToExposedSession(session);
    this.state.sessions[session.id] = exposedSession;
    this.events.opened.emit(exposedSession);
  }
  #sessionClosed(session) {
    if (!(session.id in this.state.sessions)) {
      return;
    }
    delete this.state.sessions[session.id];
    this.events.closed.emit(this.#convertToExposedSession(session));
  }
  #subscriptionsChanged(session, subscription) {
    if (session.isPase) {
      return;
    }
    if (session.subscriptions.has(subscription)) {
      this.events.subscriptionAdded.emit(subscription);
    }
    const sessionEntry = this.state.sessions[session.id];
    if (sessionEntry === void 0) {
      return;
    }
    sessionEntry.numberOfActiveSubscriptions = session.subscriptions.size;
    this.state.sessions[session.id] = sessionEntry;
    this.events.subscriptionsChanged.emit(sessionEntry);
  }
  #enterOfflineMode() {
    this.state.sessions = {};
  }
}
((SessionsBehavior2) => {
  class State {
    sessions = {};
  }
  SessionsBehavior2.State = State;
  class Events extends EventEmitter {
    opened = Observable();
    closed = Observable();
    subscriptionsChanged = Observable();
    subscriptionAdded = Observable();
  }
  SessionsBehavior2.Events = Events;
})(SessionsBehavior || (SessionsBehavior = {}));
export {
  SessionsBehavior
};
//# sourceMappingURL=SessionsBehavior.js.map
