import * as tsplus_module_1 from "@tsplus/stdlib/data/Maybe/definition";
import * as tsplus_module_2 from "@effect/core/io/Effect/operations/map";
import * as tsplus_module_3 from "@tsplus/stdlib/data/Tuple/make";
import * as tsplus_module_4 from "@effect/core/io/Effect/operations/succeed";
import * as tsplus_module_5 from "@effect/core/io/Effect/operations/flatten";
import { Exited, Running } from "@effect/core/io/Scope/ReleaseMap/_internal/State";
import { next } from "@effect/core/io/Scope/ReleaseMap/operations/_internal/next";
/**
 * Adds a finalizer to the finalizers associated with this scope. If the
 * scope is still open, a key will be returned. This is an identifier that can
 * be used to activate this finalizer and remove it from the map. If the scope
 * has been closed, the finalizer will be executed immediately (with the `Exit`
 * value with which the scope has ended) and no key will be returned.
 *
 * @tsplus fluent ets/ReleaseMap addIfOpen
 */

export function addIfOpen_(self, finalizer, __tsplusTrace) {
  return tsplus_module_5.flattenNow(self.ref.modify(s => {
    switch (s._tag) {
      case "Exited":
        {
          return tsplus_module_3.make(tsplus_module_2.map_(finalizer(s.exit), () => tsplus_module_1.none, __tsplusTrace), new Exited(next(s.nextKey), s.exit, s.update));
        }

      case "Running":
        {
          const finalizers = s.finalizers().set(s.nextKey, finalizer);
          return tsplus_module_3.make(tsplus_module_4.succeed(() => tsplus_module_1.some(s.nextKey), __tsplusTrace), new Running(next(s.nextKey), finalizers, s.update));
        }
    }
  }, __tsplusTrace), __tsplusTrace);
}
/**
 * Adds a finalizer to the finalizers associated with this scope. If the
 * scope is still open, a key will be returned. This is an identifier that can
 * be used to activate this finalizer and remove it from the map. If the scope
 * has been closed, the finalizer will be executed immediately (with the `Exit`
 * value with which the scope has ended) and no key will be returned.
 *
 * @tsplus static ets/ReleaseMap/Aspects addIfOpen
 */

export const addIfOpen = (finalizer, __tsplusTrace) => self => addIfOpen_(self, finalizer, __tsplusTrace);
//# sourceMappingURL=addIfOpen.mjs.map