"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
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 ZWaveSerialStream_exports = {};
__export(ZWaveSerialStream_exports, {
  ZWaveSerialStream: () => ZWaveSerialStream,
  ZWaveSerialStreamFactory: () => ZWaveSerialStreamFactory,
  isZWaveSerialBindingFactory: () => isZWaveSerialBindingFactory
});
module.exports = __toCommonJS(ZWaveSerialStream_exports);
var import_shared = require("@zwave-js/shared");
var import_Logger = require("../log/Logger.js");
var import_MessageHeaders = require("../message/MessageHeaders.js");
var import_ZWaveSerialParser = require("../plumbing/ZWaveSerialParser.js");
var import_definitions = require("./definitions.js");
function isZWaveSerialBindingFactory(obj) {
  return typeof obj === "function" && obj.length === 0;
}
__name(isZWaveSerialBindingFactory, "isZWaveSerialBindingFactory");
class ZWaveSerialStreamFactory {
  static {
    __name(this, "ZWaveSerialStreamFactory");
  }
  constructor(binding, loggers) {
    this.binding = binding;
    this.logger = new import_Logger.SerialLogger(loggers);
  }
  binding;
  logger;
  async createStream() {
    const { source, sink } = await this.binding();
    return new ZWaveSerialStream(source, sink, this.logger);
  }
}
class ZWaveSerialStream {
  static {
    __name(this, "ZWaveSerialStream");
  }
  constructor(source, sink, logger) {
    this.logger = logger;
    this.#abort = new AbortController();
    const { readable: input, writable } = new TransformStream();
    this.writable = writable;
    const sinkStream = new WritableStream(sink);
    void input.pipeTo(sinkStream, { signal: this.#abort.signal }).catch(import_shared.noop);
    this.parser = new import_ZWaveSerialParser.ZWaveSerialParser(logger, this.#abort.signal);
    this.readable = this.parser.readable;
    const sourceStream = new ReadableStream(source);
    void sourceStream.pipeTo(this.parser.writable, {
      signal: this.#abort.signal
    }).catch((_e) => {
      this._isOpen = false;
    });
  }
  logger;
  // Public interface to let consumers read from and write to this stream
  readable;
  writable;
  // Signal to close the underlying stream
  #abort;
  // Serial API parser
  parser;
  // Allow switching between modes
  get mode() {
    return this.parser.mode;
  }
  set mode(mode) {
    this.parser.mode = mode;
  }
  // Allow ignoring the high nibble of an ACK once to work around an issue in the 700 series firmware
  ignoreAckHighNibbleOnce() {
    this.parser.ignoreAckHighNibbleOnce();
  }
  async close() {
    this._isOpen = false;
    if (this._writer) {
      try {
        this._writer?.releaseLock();
        this._writer = void 0;
        await this.writable.close();
      } catch {
      }
    }
    this.#abort.abort();
    return Promise.resolve();
  }
  _isOpen = true;
  get isOpen() {
    return this._isOpen;
  }
  _writer;
  async writeAsync(data) {
    if (!this.isOpen) {
      throw new Error("The serial port is not open!");
    }
    if (this.mode === import_definitions.ZWaveSerialMode.SerialAPI && data.length === 1) {
      switch (data[0]) {
        case import_MessageHeaders.MessageHeaders.ACK:
          this.logger.ACK("outbound");
          break;
        case import_MessageHeaders.MessageHeaders.CAN:
          this.logger.CAN("outbound");
          break;
        case import_MessageHeaders.MessageHeaders.NAK:
          this.logger.NAK("outbound");
          break;
      }
    } else {
      this.logger.data("outbound", data);
    }
    this._writer ??= this.writable.getWriter();
    await this._writer.write(data);
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ZWaveSerialStream,
  ZWaveSerialStreamFactory,
  isZWaveSerialBindingFactory
});
//# sourceMappingURL=ZWaveSerialStream.js.map
