import * as tsplus_module_1 from "@tsplus/stdlib/data/Maybe/definition";
import * as tsplus_module_2 from "@effect/core/stream/Channel/operations/pipeTo";
import * as tsplus_module_3 from "@effect/core/stream/Channel/operations/write";
import * as tsplus_module_4 from "@effect/core/stream/Channel/operations/zipRight";
import * as tsplus_module_5 from "@effect/core/stream/Channel/operations/failCause";
import * as tsplus_module_6 from "@effect/core/stream/Channel/operations/unit";
import * as tsplus_module_7 from "@tsplus/stdlib/collections/Chunk/single";
import * as tsplus_module_8 from "@tsplus/stdlib/data/Maybe/fold";
import * as tsplus_module_9 from "@effect/core/stream/Channel/operations/readWithCause";
import * as tsplus_module_10 from "@tsplus/stdlib/collections/Chunk/empty";
import * as tsplus_module_11 from "@tsplus/stdlib/data/Tuple/make";
import * as tsplus_module_12 from "@tsplus/stdlib/collections/Chunk/append";
import * as tsplus_module_13 from "@tsplus/stdlib/collections/Chunk/reduce";
import { concreteStream, StreamInternal } from "@effect/core/stream/Stream/operations/_internal/StreamInternal";
/**
 * Creates a stream that groups on adjacent keys, calculated by function f.
 *
 * @tsplus fluent ets/Stream groupAdjacentBy
 */

export function groupAdjacentBy_(self, f, __tsplusTrace) {
  void 0;
  return new StreamInternal(tsplus_module_2.pipeTo_(self.channel, () => chunkAdjacent(tsplus_module_1.none, f, __tsplusTrace)));
}
/**
 * Creates a stream that groups on adjacent keys, calculated by function f.
 *
 * @tsplus static ets/Stream/Aspects groupAdjacentBy
 */

export const groupAdjacentBy = (f, __tsplusTrace) => self => groupAdjacentBy_(self, f, __tsplusTrace);

function chunkAdjacent(buffer, f, __tsplusTrace) {
  return tsplus_module_9.readWithCause(chunk => {
    const {
      tuple: [outputs, newBuffer]
    } = go(chunk, buffer, f, __tsplusTrace);
    return tsplus_module_4.zipRight_(tsplus_module_3.write(() => outputs), () => chunkAdjacent(newBuffer, f, __tsplusTrace));
  }, cause => tsplus_module_5.failCause(() => cause), () => tsplus_module_8.fold_(buffer, () => tsplus_module_6.unit, o => tsplus_module_3.write(() => tsplus_module_7.single(o))));
}

function go(input, state, f, __tsplusTrace) {
  return tsplus_module_13.reduce_(input, tsplus_module_11.make(tsplus_module_10.empty(), state), ({
    tuple: [os, o]
  }, a) => tsplus_module_8.fold_(o, () => tsplus_module_11.make(os, tsplus_module_1.some(tsplus_module_11.make(f(a), tsplus_module_7.single(a)))), agg => {
    const k2 = f(a);
    const {
      tuple: [k, aggregated]
    } = agg;

    if (k === k2) {
      return tsplus_module_11.make(os, tsplus_module_1.some(tsplus_module_11.make(k, tsplus_module_12.append_(aggregated, a))));
    } else {
      return tsplus_module_11.make(tsplus_module_12.append_(os, agg), tsplus_module_1.some(tsplus_module_11.make(k2, tsplus_module_7.single(a))));
    }
  }));
}
//# sourceMappingURL=groupAdjacentBy.mjs.map