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 "@tsplus/stdlib/data/Maybe/fromNullable";
import * as tsplus_module_5 from "@effect/core/io/Effect/operations/succeed";
import * as tsplus_module_6 from "@effect/core/io/Effect/operations/flatten";
import { Exited, Running } from "@effect/core/io/Scope/ReleaseMap/_internal/State";
/**
 * Replaces the finalizer associated with this key and returns it. If the
 * finalizers associated with this scope have already been run this
 * finalizer will be run immediately.
 *
 * @tsplus fluent ets/ReleaseMap replace
 */

export function replace_(self, key, finalizer, __tsplusTrace) {
  return tsplus_module_6.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(s.nextKey, s.exit, s.update));
        }

      case "Running":
        {
          const finalizers = s.finalizers();
          const oldFinalizer = tsplus_module_4.fromNullable(finalizers.get(key));
          const newFinalizers = finalizers.set(key, finalizer);
          return tsplus_module_3.make(tsplus_module_5.succeed(() => oldFinalizer, __tsplusTrace), new Running(s.nextKey, newFinalizers, s.update));
        }
    }
  }, __tsplusTrace), __tsplusTrace);
}
/**
 * Replaces the finalizer associated with this key and returns it. If the
 * finalizers associated with this scope have already been run this
 * finalizer will be run immediately.
 *
 * @tsplus static ets/ReleaseMap/Aspects replace
 */

export const replace = (key, finalizer, __tsplusTrace) => self => replace_(self, key, finalizer, __tsplusTrace);
//# sourceMappingURL=replace.mjs.map