import { DropdownEvents } from '../dropdown';
export default class ModalService {
  static instance = null;
  constructor() {
    this.modalStack = [];
  }
  static getInstance() {
    if (this.instance === null) {
      // TODO
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      this.instance = new this();
    }
    return this.instance;
  }
  registerModal({
    key = null,
    triggerClose = () => {},
    forceOpen = false,
    supportsStacking = false
  }) {
    const modal = {
      key,
      triggerClose,
      forceOpen,
      supportsStacking
    };
    if (this.modalStack.length > 0) {
      const latestModal = this.modalStack[this.modalStack.length - 1];

      // If the last modal supports stacking, open the new one on top
      if (latestModal.supportsStacking) {
        this.modalStack = [...this.modalStack, modal];
        return;
      }

      // If the last modal isn't persistent, and we are trying to open a different one,
      // replace it with the new one
      if (!latestModal.forceOpen && latestModal.key !== modal.key) {
        latestModal.triggerClose?.();
        this.modalStack = [...this.modalStack.slice(0, this.modalStack.length - 1), modal];
        return;
      }

      // If the last modal is persistent, don't open the new one and notify its parent
      // that is has been closed, so it can reconcile the state
      if (latestModal.forceOpen) {
        modal.triggerClose();
      }
    } else {
      this.modalStack = [modal];
    }
  }
  clearModal(key) {
    this.modalStack = this.modalStack.filter(modal => modal.key !== key);
  }
  closeAll(modalKeysToKeep = []) {
    this.modalStack.forEach(modal => {
      if (!modalKeysToKeep.includes(modal.key)) {
        modal.triggerClose?.();
        this.clearModal(modal.key);
      }
    });
  }
  closeAllDropdowns() {
    DropdownEvents.closeAllDropdowns();
  }
}