import * as tsplus_module_1 from "@tsplus/stdlib/data/AtomicReference";
import * as tsplus_module_2 from "@tsplus/stdlib/collections/Chunk/isNonEmpty";
import * as tsplus_module_3 from "@tsplus/stdlib/collections/Chunk/filter";
import * as tsplus_module_4 from "@effect/core/stream/Channel/operations/writeChunk";
import * as tsplus_module_5 from "@tsplus/stdlib/collections/Chunk/empty";
import * as tsplus_module_6 from "@effect/core/stream/Channel/operations/succeed";
import * as tsplus_module_7 from "@effect/core/stream/Channel/operations/flatMap";
import * as tsplus_module_8 from "@effect/core/stream/Channel/operations/identity";
import * as tsplus_module_9 from "@effect/core/stream/Channel/operations/zipRight";
import * as tsplus_module_10 from "@effect/core/stream/Channel/operations/pipeTo";
import * as tsplus_module_11 from "@effect/core/stream/Channel/operations/as";
import * as tsplus_module_12 from "@effect/core/stream/Channel/operations/doneCollect";
import * as tsplus_module_13 from "@effect/core/stream/Channel/operations/suspend";
import * as tsplus_module_14 from "@effect/core/stream/Channel/operations/foldChannel";
import { concreteSink, SinkInternal } from "@effect/core/stream/Sink/operations/_internal/SinkInternal";
/**
 * @tsplus fluent ets/Sink foldSink
 */

export function foldSink_(self, failure, success, __tsplusTrace) {
  void 0;
  return new SinkInternal(tsplus_module_14.foldChannel_(tsplus_module_12.doneCollect(self.channel), err => {
    const result = failure(err);
    void 0;
    return result.channel;
  }, ({
    tuple: [leftovers, z]
  }) => tsplus_module_13.suspend(() => {
    const leftoversRef = new tsplus_module_1.AtomicReference(tsplus_module_3.filter_(leftovers, chunk => tsplus_module_2.isNonEmpty(chunk)));
    const refReader = tsplus_module_7.flatMap_(tsplus_module_6.succeed(() => leftoversRef.getAndSet(tsplus_module_5.empty())), chunk => tsplus_module_4.writeChunk(chunk));
    const passThrough = tsplus_module_8.identity();
    const continuationSink = tsplus_module_10.pipeTo_(tsplus_module_9.zipRight_(refReader, () => passThrough), () => {
      const result = success(z);
      void 0;
      return result.channel;
    });
    return tsplus_module_7.flatMap_(tsplus_module_12.doneCollect(continuationSink), ({
      tuple: [newLeftovers, z1]
    }) => tsplus_module_9.zipRight_(tsplus_module_7.flatMap_(tsplus_module_6.succeed(() => leftoversRef.get), chunk => tsplus_module_4.writeChunk(chunk)), () => tsplus_module_11.as_(tsplus_module_4.writeChunk(newLeftovers), () => z1)));
  })));
}
/**
 * @tsplus static ets/Sink/Aspects foldSink
 */

export const foldSink = (failure, success, __tsplusTrace) => self => foldSink_(self, failure, success, __tsplusTrace);
//# sourceMappingURL=foldSink.mjs.map