"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 CLIParser_exports = {};
__export(CLIParser_exports, {
  CLIParser: () => CLIParser
});
module.exports = __toCommonJS(CLIParser_exports);
var import_shared = require("@zwave-js/shared");
var import_MessageHeaders = require("../message/MessageHeaders.js");
var import_ZWaveSerialFrame = require("./ZWaveSerialFrame.js");
function isFlowControl(byte) {
  return byte === import_MessageHeaders.XModemMessageHeaders.ACK || byte === import_MessageHeaders.XModemMessageHeaders.NAK || byte === import_MessageHeaders.XModemMessageHeaders.CAN || byte === import_MessageHeaders.XModemMessageHeaders.C;
}
__name(isFlowControl, "isFlowControl");
function normalizeLine(line) {
  return line.startsWith("\r") ? line.slice(1) : line;
}
__name(normalizeLine, "normalizeLine");
function isPromptLine(line) {
  const normalizedLine = normalizeLine(line).trimEnd();
  return normalizedLine === ">" || normalizedLine.startsWith("> ");
}
__name(isPromptLine, "isPromptLine");
class CLIParser extends TransformStream {
  static {
    __name(this, "CLIParser");
  }
  logger;
  constructor(logger) {
    let receiveBuffer = "";
    let flushTimeout;
    function wrapChunk(chunk) {
      return {
        type: import_ZWaveSerialFrame.ZWaveSerialFrameType.CLI,
        data: chunk
      };
    }
    __name(wrapChunk, "wrapChunk");
    const transformer = {
      transform(chunk, controller) {
        flushTimeout?.clear();
        flushTimeout = void 0;
        receiveBuffer += import_shared.Bytes.view(chunk).toString("utf8");
        while (receiveBuffer.length > 0) {
          const charCode = receiveBuffer.charCodeAt(0);
          if (!isFlowControl(charCode))
            break;
          logger?.data("inbound", Uint8Array.from([charCode]));
          controller.enqueue(wrapChunk({
            type: import_ZWaveSerialFrame.CLIChunkType.FlowControl,
            command: charCode
          }));
          receiveBuffer = receiveBuffer.slice(1);
        }
        const lines = receiveBuffer.split("\n");
        if (lines.some(isPromptLine)) {
          const output = lines.map((line) => {
            if (!isPromptLine(line))
              return line;
            const normalized = normalizeLine(line);
            return normalized.startsWith("> ") ? normalized.slice(2) : "";
          }).join("\n").trim();
          if (output) {
            logger?.message(output, "inbound");
            controller.enqueue(wrapChunk({
              type: import_ZWaveSerialFrame.CLIChunkType.Message,
              message: output
            }));
          }
          controller.enqueue(wrapChunk({
            type: import_ZWaveSerialFrame.CLIChunkType.Prompt
          }));
          receiveBuffer = "";
        } else if (/^\[[A-Z]\] /.test(receiveBuffer)) {
          logger?.message(receiveBuffer, "inbound");
          controller.enqueue(wrapChunk({
            type: import_ZWaveSerialFrame.CLIChunkType.Message,
            message: receiveBuffer
          }));
          receiveBuffer = "";
        }
        if (receiveBuffer) {
          flushTimeout = (0, import_shared.setTimer)(() => {
            flushTimeout = void 0;
            logger?.message(receiveBuffer, "inbound");
            controller.enqueue(wrapChunk({
              type: import_ZWaveSerialFrame.CLIChunkType.Message,
              message: receiveBuffer
            }));
            receiveBuffer = "";
          }, 500);
        }
      }
    };
    super(transformer);
    this.logger = logger;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CLIParser
});
//# sourceMappingURL=CLIParser.js.map
