// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

import { createLPS } from "./_common.ts";

import type {
  DelimiterDisposition,
  DelimiterStreamOptions,
} from "./delimiter_stream.ts";

/**
 * Transform a stream `string` into a stream where each chunk is divided by a
 * given delimiter.
 *
 * If you are working with a stream of `Uint8Array`, consider using {@linkcode DelimiterStream}.
 *
 * If you want to split by a newline, consider using {@linkcode TextLineStream}.
 *
 * @example Comma-separated values
 * ```ts
 * import { TextDelimiterStream } from "@std/streams/text-delimiter-stream";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const stream = ReadableStream.from([
 *   "alice,20,",
 *   ",US,",
 * ]);
 *
 * const valueStream = stream.pipeThrough(new TextDelimiterStream(","));
 *
 * assertEquals(
 *   await Array.fromAsync(valueStream),
 *   ["alice", "20", "", "US", ""],
 * );
 * ```
 *
 * @example Semicolon-separated values with suffix disposition
 * ```ts
 * import { TextDelimiterStream } from "@std/streams/text-delimiter-stream";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const stream = ReadableStream.from([
 *   "const a = 42;;let b =",
 *   " true;",
 * ]);
 *
 * const valueStream = stream.pipeThrough(
 *   new TextDelimiterStream(";", { disposition: "suffix" }),
 * );
 *
 * assertEquals(
 *   await Array.fromAsync(valueStream),
 *   ["const a = 42;", ";", "let b = true;", ""],
 * );
 * ```
 */
export class TextDelimiterStream extends TransformStream<string, string> {
  #buf = "";
  #delimiter: string;
  #inspectIndex = 0;
  #matchIndex = 0;
  #delimLPS: Uint8Array;
  #disp: DelimiterDisposition;

  /**
   * Constructs a new instance.
   *
   * @param delimiter A delimiter to split the stream by.
   * @param options Options for the stream.
   *
   * @example Comma as a delimiter
   * ```ts no-assert
   * import { TextDelimiterStream } from "@std/streams/text-delimiter-stream";
   *
   * const delimiterStream = new TextDelimiterStream(",");
   * ```
   *
   * @example Semicolon as a delimiter, and disposition set to `"suffix"`
   * ```ts no-assert
   * import { TextDelimiterStream } from "@std/streams/text-delimiter-stream";
   *
   * const delimiterStream = new TextDelimiterStream(",", {
   *   disposition: "suffix",
   * });
   * ```
   */
  constructor(
    delimiter: string,
    options: DelimiterStreamOptions = { disposition: "discard" },
  ) {
    super({
      transform: (chunk, controller) => {
        this.#handle(chunk, controller);
      },
      flush: (controller) => {
        controller.enqueue(this.#buf);
      },
    });

    this.#delimiter = delimiter;
    this.#delimLPS = createLPS(new TextEncoder().encode(delimiter));
    this.#disp = options.disposition ?? "discard";
  }

  #handle(
    chunk: string,
    controller: TransformStreamDefaultController<string>,
  ) {
    this.#buf += chunk;
    let localIndex = 0;
    while (this.#inspectIndex < this.#buf.length) {
      if (chunk[localIndex] === this.#delimiter[this.#matchIndex]) {
        this.#inspectIndex++;
        localIndex++;
        this.#matchIndex++;
        if (this.#matchIndex === this.#delimiter.length) {
          // Full match
          const start = this.#inspectIndex - this.#delimiter.length;
          const end = this.#disp === "suffix" ? this.#inspectIndex : start;
          const copy = this.#buf.slice(0, end);
          controller.enqueue(copy);
          const shift = this.#disp === "prefix" ? start : this.#inspectIndex;
          this.#buf = this.#buf.slice(shift);
          this.#inspectIndex = this.#disp === "prefix"
            ? this.#delimiter.length
            : 0;
          this.#matchIndex = 0;
        }
      } else {
        if (this.#matchIndex === 0) {
          this.#inspectIndex++;
          localIndex++;
        } else {
          this.#matchIndex = this.#delimLPS[this.#matchIndex - 1]!;
        }
      }
    }
  }
}

// denoCacheMetadata={"headers":{"content-type":"text/typescript","accept-ranges":"bytes","access-control-expose-headers":"*","cache-control":"public, max-age=31536000, immutable","set-cookie":"__cf_bm=cPGS5hNOks1jVzsGvHwOWrdRzkjpJh6ux0V04KD.3XI-1785241875.1819065-1.0.1.1-gBNW3YEa3aS4W0x2OJGLveafreF8gxbKhUzTlgA0rpuBP6VXW3nBDpNskGNLtfh1rVoETDRP9TsB_PA7d011UXNPc_uv5__7DwlCcxrr37S0dM0SVdzY.eHM_D2ePrr8; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","alt-svc":"h3=\":443\"; ma=86400","server":"cloudflare","cf-cache-status":"HIT","x-jsr-backend":"modules","access-control-allow-origin":"*","vary":"Origin","age":"2817330","x-robots-tag":"noindex","cf-ray":"a223e657dac37db6-LAX","date":"Tue, 28 Jul 2026 12:31:15 GMT","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=Mm8BgzDcA5KoD42WiiX3kVw0T0bHfERStApmcPkwJfMfrCoAQ7f5PrCsIdHjS6%2BXzu40Ktg7TB0dwT%2B22n9%2FvvrjRrAtaBw0a%2FAxtk5sMA9hXlAaSKhYuEQ%3D\"}]}","content-length":"4019","etag":"\"f010623bf2636d27335563766b9c8127\"","cross-origin-resource-policy":"cross-origin","x-content-type-options":"nosniff","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}"},"url":"https://jsr.io/@std/streams/0.224.5/text_delimiter_stream.ts","time":1785241875}