"use strict"
var __createBinding =
  (this && this.__createBinding) ||
  (Object.create
    ? function (o, m, k, k2) {
        if (k2 === undefined) k2 = k
        Object.defineProperty(o, k2, {
          enumerable: true,
          get: function () {
            return m[k]
          }
        })
      }
    : function (o, m, k, k2) {
        if (k2 === undefined) k2 = k
        o[k2] = m[k]
      })
var __setModuleDefault =
  (this && this.__setModuleDefault) ||
  (Object.create
    ? function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v })
      }
    : function (o, v) {
        o["default"] = v
      })
var __importStar =
  (this && this.__importStar) ||
  function (mod) {
    if (mod && mod.__esModule) return mod
    var result = {}
    if (mod != null)
      for (var k in mod)
        if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
          __createBinding(result, mod, k)
    __setModuleDefault(result, mod)
    return result
  }
Object.defineProperty(exports, "__esModule", { value: true })
exports.chainParSwitch = void 0
const Function_1 = require("../../Function")
const P = __importStar(require("../../Promise"))
const Q = __importStar(require("../../Queue"))
const SM = __importStar(require("../../Semaphore"))
const Pull = __importStar(require("../../Stream/Pull"))
const T = __importStar(require("../_internal/effect"))
const F = __importStar(require("../_internal/fiber"))
const M = __importStar(require("../_internal/managed"))
const chain = __importStar(require("./chain"))
const definitions_1 = require("./definitions")
const forEach = __importStar(require("./forEach"))
const managed_1 = require("./managed")
const tap = __importStar(require("./tap"))
/**
 * Maps each element of this stream to another stream and returns the non-deterministic merge
 * of those streams, executing up to `n` inner streams concurrently. When a new stream is created
 * from an element of the source stream, the oldest executing stream is cancelled. Up to `bufferSize`
 * elements of the produced streams may be buffered in memory by this operator.
 */
function chainParSwitch(n, bufferSize = 16) {
  return (f) => (self) => {
    return new definitions_1.Stream(
      M.withChildren((getChildren) =>
        M.map_(
          M.tap_(
            M.bind_(
              M.bind_(
                M.bind_(
                  M.bind_(M.do, "out", () =>
                    T.toManagedRelease_(Q.makeBounded(bufferSize), Q.shutdown)
                  ),
                  "permits",
                  () => T.toManaged(SM.makeSemaphore(n))
                ),
                "innerFailure",
                () => T.toManaged(P.make())
              ),
              "cancelers",
              () => T.toManagedRelease_(Q.makeBounded(n), Q.shutdown)
            ),
            ({ cancelers, innerFailure, out, permits }) =>
              M.fork(
                M.foldCauseM_(
                  forEach.forEachManaged_(self, (a) =>
                    T.asUnit(
                      T.tap_(
                        T.tap_(
                          T.let_(
                            T.tap_(
                              T.tap_(
                                T.bind_(
                                  T.bind_(
                                    T.bind_(T.do, "canceler", () => P.make()),
                                    "latch",
                                    () => P.make()
                                  ),
                                  "size",
                                  () => Q.size(cancelers)
                                ),
                                ({ size }) => {
                                  if (size < n) {
                                    return T.unit
                                  } else {
                                    return T.asUnit(
                                      T.chain_(Q.take(cancelers), (_) =>
                                        T.succeed(undefined)
                                      )
                                    )
                                  }
                                }
                              ),
                              ({ canceler }) => Q.offer_(cancelers, canceler)
                            ),
                            "innerStream",
                            ({ latch }) =>
                              T.foldCauseM_(
                                forEach.forEachChunk((o2s) =>
                                  T.asUnit(Q.offer_(out, T.succeed(o2s)))
                                )(
                                  chain.chain((_) => f(a))(
                                    tap.tap((_) => P.succeed_(latch, undefined))(
                                      (0, managed_1.managed)(
                                        SM.withPermitManaged(permits)
                                      )
                                    )
                                  )
                                ),
                                (cause) =>
                                  T.asUnit(
                                    T.zipRight_(
                                      Q.offer_(out, Pull.halt(cause)),
                                      P.fail_(innerFailure, cause)
                                    )
                                  ),
                                (_) => T.unit
                              )
                          ),
                          ({ canceler, innerStream }) =>
                            T.fork(T.race_(innerStream, P.await(canceler)))
                        ),
                        ({ latch }) => P.await(latch)
                      )
                    )
                  ),
                  (cause) =>
                    T.toManaged(
                      T.asUnit(
                        T.zipRight_(
                          T.chain_(getChildren, (_) => F.interruptAll(_)),
                          Q.offer_(out, Pull.halt(cause))
                        )
                      )
                    ),
                  (_) =>
                    T.toManaged(
                      T.raceWith_(
                        P.await(innerFailure),
                        SM.withPermits_(T.unit, permits, n),
                        (_, permitAcquisition) =>
                          T.zipRight_(
                            T.chain_(getChildren, F.interruptAll),
                            T.asUnit(F.interrupt(permitAcquisition))
                          ),
                        (_, failureAwait) =>
                          T.zipRight_(
                            Q.offer_(out, Pull.end),
                            T.asUnit(F.interrupt(failureAwait))
                          )
                      )
                    )
                )
              )
          ),
          ({ out }) => T.flatten(Q.take(out))
        )
      )
    )
  }
}
exports.chainParSwitch = chainParSwitch
//# sourceMappingURL=chainParSwitch.js.map
