/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { BtpCodec } from "#codec/BtpCodec.js";
import { Days, Duration, Millis, Minutes, Seconds } from "@matter/general";
import { Advertisement } from "../Advertisement.js";
const EARLY_INTERVAL_SLEEP = Seconds(30);
const LATE_INTERVAL_SLEEP = Millis(Minutes(15) - EARLY_INTERVAL_SLEEP);
const EXTENDED_INTERVAL_SLEEP = Millis(Days(2) - LATE_INTERVAL_SLEEP);
class BleAdvertisement extends Advertisement {
  constructor(advertiser, description) {
    super(advertiser, "ble:commissioning", description);
  }
  async run(context) {
    const {
      peripheral,
      config: { earlyInterval, lateInterval, extendedInterval }
    } = this.advertiser;
    let aad = this.advertiser.config.aad;
    let timeout = this.advertiser.config.timeout;
    let advertisementData = this.#encodedAdvertisement;
    let isExtended = false;
    const intervals = [
      { sleepTime: EARLY_INTERVAL_SLEEP, broadcastInterval: earlyInterval },
      { sleepTime: LATE_INTERVAL_SLEEP, broadcastInterval: lateInterval },
      { sleepTime: EXTENDED_INTERVAL_SLEEP, broadcastInterval: extendedInterval }
    ];
    try {
      for (const { sleepTime, broadcastInterval } of intervals) {
        if (!isExtended && this.isPrivacyMasked) {
          isExtended = true;
          advertisementData = this.#encodedAdvertisement;
          aad = void 0;
        }
        await peripheral.advertise(advertisementData, aad, broadcastInterval);
        await context.sleep("BLE advertisement interval", Duration.min(timeout, sleepTime));
        timeout = Millis(timeout - sleepTime);
        if (timeout <= 0) {
          break;
        }
      }
    } finally {
      await peripheral.stopAdvertising();
    }
  }
  get #encodedAdvertisement() {
    const { discriminator, vendorId, productId } = this.description;
    const { isPrivacyMasked: isExtendedAnnouncement } = this;
    return BtpCodec.encodeBleAdvertisementData(
      discriminator,
      isExtendedAnnouncement ? 0 : vendorId,
      isExtendedAnnouncement ? 0 : productId,
      !isExtendedAnnouncement && !!this.advertiser.config.aad?.byteLength,
      isExtendedAnnouncement
    );
  }
  isDuplicate(other) {
    return other !== this && other.service === this.service;
  }
}
export {
  BleAdvertisement
};
//# sourceMappingURL=BleAdvertisement.js.map
