import * as tsplus_module_1 from "@effect/core/stm/TRef/operations/unsafeGet";
import * as tsplus_module_2 from "@effect/core/stm/TRef/operations/unsafeSet";
import * as tsplus_module_3 from "@effect/core/stm/THub/definition";
import * as tsplus_module_4 from "@effect/core/stm/THub/operations/_internal/InternalNode";
import * as tsplus_module_5 from "@tsplus/stdlib/collections/HashSet/remove";
import * as tsplus_module_6 from "@effect/core/stm/STM/operations/effect";
import { concreteTDequeue } from "@effect/core/stm/THub/operations/_internal/InternalTDequeue";
/**
 * Views the next element in the queue without removing it, retrying if the
 * queue is empty.
 *
 * @tsplus getter ets/THub/TDequeue shutdown
 */

export function shutdown(self) {
  void 0;
  return tsplus_module_6.effect(journal => {
    let currentSubscriberHead = tsplus_module_1.unsafeGet_(self.subscriberHead, journal);

    if (currentSubscriberHead != null) {
      tsplus_module_2.unsafeSet_(self.subscriberHead, undefined, journal);
      let loop = true;

      while (loop) {
        const node = tsplus_module_1.unsafeGet_(currentSubscriberHead, journal);

        if (node == null) {
          loop = false;
        } else {
          const head = node.head;
          const tail = node.tail;

          if (head != null) {
            const subscribers = node.subscribers;

            if (subscribers == 1) {
              const size = tsplus_module_1.unsafeGet_(self.hubSize, journal);
              const updatedNode = tsplus_module_4.make(undefined, 0, node.tail);
              tsplus_module_2.unsafeSet_(currentSubscriberHead, updatedNode, journal);
              tsplus_module_2.unsafeSet_(self.publisherHead, tail, journal);
              tsplus_module_2.unsafeSet_(self.hubSize, size - 1, journal);
            } else {
              const updatedNode = tsplus_module_4.make(undefined, subscribers - 1, node.tail);
              tsplus_module_2.unsafeSet_(currentSubscriberHead, updatedNode, journal);
            }
          }

          currentSubscriberHead = tail;
        }
      }

      const currentSubscriberCount = tsplus_module_1.unsafeGet_(self.subscriberCount, journal);
      tsplus_module_2.unsafeSet_(self.subscriberCount, currentSubscriberCount - 1, journal);
      tsplus_module_2.unsafeSet_(self.subscribers, tsplus_module_5.remove_(tsplus_module_1.unsafeGet_(self.subscribers, journal), self.subscriberHead), journal);
    }
  });
}
//# sourceMappingURL=shutdown.mjs.map