"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
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();
};
var StandardTime_exports = {};
__export(StandardTime_exports, {
  StandardTime: () => StandardTime,
  StandardTimer: () => StandardTimer
});
module.exports = __toCommonJS(StandardTime_exports);
var import_MatterError = require("#MatterError.js");
var import_Boot = require("#util/Boot.js");
var import_identifier_case = require("#util/identifier-case.js");
var import_Lifetime = require("#util/Lifetime.js");
var import_Time = require("./Time.js");
var import_TimeUnit = require("./TimeUnit.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
class StandardTime extends import_Time.Time {
  getTimer(name, duration, callback) {
    return new StandardTimer(name, duration, callback, false);
  }
  getPeriodicTimer(name, duration, callback) {
    return new StandardTimer(name, duration, callback, true);
  }
}
{
  let macrotask;
  const { setImmediate } = globalThis;
  if (setImmediate !== void 0) {
    macrotask = () => new Promise((resolve) => setImmediate(resolve));
  } else if (typeof MessageChannel !== "undefined") {
    macrotask = () => new Promise((resolve) => {
      const channel = new MessageChannel();
      channel.port1.onmessage = () => resolve();
      channel.port2.postMessage(null);
    });
  } else {
    macrotask = () => new Promise((resolve) => setTimeout(resolve, 0));
  }
  Object.defineProperty(StandardTime.prototype, "macrotask", { get: macrotask });
}
class StandardTimer {
  constructor(name, duration, callback, isPeriodic) {
    this.name = name;
    this.callback = callback;
    this.isPeriodic = isPeriodic;
    this.interval = duration;
  }
  name;
  callback;
  isPeriodic;
  #timerId;
  #utility = false;
  #interval = import_TimeUnit.Instant;
  // Real value installed in constructor
  isRunning = false;
  get systemId() {
    return Number(this.#timerId);
  }
  /**
   * The timer's interval.
   *
   * You can change this value but changes have no effect until the timer restarts.
   */
  set interval(interval) {
    if (interval < 0 || interval > 2147483647) {
      throw new import_MatterError.ImplementationError(
        `Invalid intervalMs: ${interval}. The value must be between 0 and 32-bit maximum value (2147483647)`
      );
    }
    this.#interval = interval;
  }
  get interval() {
    return this.#interval;
  }
  get utility() {
    return this.#utility;
  }
  set utility(utility) {
    if (utility === this.#utility) {
      return;
    }
    if (this.#timerId !== void 0) {
      const timerId = this.#timerId;
      if (utility) {
        timerId.unref?.();
      } else {
        timerId.ref?.();
      }
    }
    this.#utility = utility;
  }
  start() {
    if (this.isRunning) this.stop();
    import_Time.Time.register(this);
    this.isRunning = true;
    this.#timerId = (this.isPeriodic ? setInterval : setTimeout)(() => {
      var _stack = [];
      try {
        const lifetime = __using(_stack, (0, import_Lifetime.Lifetime)((0, import_identifier_case.decamelize)(this.name, " ")));
        if (!this.isPeriodic) {
          import_Time.Time.unregister(this);
          this.isRunning = false;
        }
        this.callback(lifetime);
      } catch (_) {
        var _error = _, _hasError = true;
      } finally {
        __callDispose(_stack, _error, _hasError);
      }
    }, this.interval);
    return this;
  }
  stop() {
    (this.isPeriodic ? clearInterval : clearTimeout)(this.#timerId);
    import_Time.Time.unregister(this);
    this.isRunning = false;
    return this;
  }
}
import_Boot.Boot.init(() => {
  import_Time.Time.default = new StandardTime();
  import_Time.Time.startup.systemMs = import_Time.Time.startup.processMs = import_Time.Time.nowMs;
  if (typeof MatterHooks !== "undefined") {
    MatterHooks?.timeSetup?.(import_Time.Time);
  }
});
//# sourceMappingURL=StandardTime.js.map
