import { Miscellaneous } from "../config";

export class ModalInstance {
  private modalOpen: boolean = false;
  private elementId: string = Miscellaneous.MODAL_ID;
  private contentId: string = Miscellaneous.MODAL_CONTENT_ID;

  public open(content: string) {
    const modal = document.getElementById(this.elementId);
    const modalContent = document.getElementById(this.contentId);
    if (!modal || this.modalOpen) {
      return;
    }

    this.modalOpen = true;
    modal.style.display = "flex";
    modal.style.animation = "fadeIn 0.25s";

    modalContent!.innerHTML = content;
    modalContent!.style.animation = "scaleUp 0.25s";
  }

  public vanish(): Promise<void> {
    const modal = document.getElementById(this.elementId);
    const modalContent = document.getElementById(this.contentId);
    return new Promise((res, _rej) => {
      if (!(modal && this.modalOpen && modalContent)) {
        res();
        return;
      }
      modal.style.animation = "fadeOut 0.25s";
      modalContent.style.animation = "scaleDown 0.25s";

      setTimeout(() => {
        modalContent.innerHTML = "";
        modal.style.display = "none";

        this.modalOpen = false;
        res();
      }, 200);
    });
  }
}

export const ModalSingleton = new ModalInstance();
