/**
 * @license
 * Copyright 2022-2026 Greg Lauckhart <greg@lauckhart.com>
 * SPDX-License-Identifier: Apache-2.0
 */
import { Producer } from "./producer.js";
import { TextWriter } from "./text-writer.js";
import { Truncator } from "./truncator.js";
import { Wrapper } from "./wrapper.js";
function Printer(targetOrOut, options) {
  let target;
  if (typeof targetOrOut === "function") {
    const writer = new TextWriter((text) => targetOrOut(text), { terminalWidth: options?.terminalWidth });
    if (options?.styleEnabled !== void 0) {
      writer.state.styleEnabled = options.styleEnabled;
    }
    target = writer;
  } else {
    target = targetOrOut;
  }
  target = options?.wrap ? new Wrapper(target, options.wrap === true ? {} : options.wrap) : target;
  let truncator;
  const printer = function Printer2(...text) {
    printer.write(...text);
  };
  function writeItems(...text) {
    const pending = [];
    function flush() {
      if (pending.length) {
        target.write(...pending);
        pending.length = 0;
      }
    }
    for (const item of text) {
      if (Printer.isRenderable(item)) {
        flush();
        item.renderTo(printer);
      } else {
        pending.push(item);
      }
    }
    flush();
  }
  Object.defineProperties(printer, {
    target: {
      get() {
        return target;
      }
    },
    state: {
      get() {
        return target.state;
      }
    },
    write: {
      value: writeItems
    },
    close: {
      value() {
        target.close();
      }
    },
    writeTruncated: {
      value(...text) {
        if (!truncator) {
          truncator = new Truncator(target, { addNewline: false });
        }
        truncator.write(...text);
      }
    },
    writeTruncatedLine: {
      value(...text) {
        const tokens = [...Producer.of(text)].filter(
          (token) => token.kind !== "newline" && token.kind !== "carriage-return"
        );
        if (!truncator) {
          truncator = new Truncator(target);
        }
        truncator.write(...tokens);
      }
    }
  });
  return printer;
}
((Printer2) => {
  function isRenderable(item) {
    return typeof item === "object" && item !== null && "renderTo" in item && typeof item.renderTo === "function";
  }
  Printer2.isRenderable = isRenderable;
})(Printer || (Printer = {}));
export {
  Printer
};
//# sourceMappingURL=printer.js.map
