import { waitForElement } from "../../requests/index.js";
import { getMenu } from "../../constants/index.js";
export default class MenuComponent {
  element;
  constructor({
    isBlocked = false,
    hasReadLater = false,
    authors = [],
    bookid = null,
    article,
  }) {
    this.isBlocked = isBlocked;
    this.hasReadLater = hasReadLater;
    this.authors = authors;
    this.bookid = bookid;
    this.article = article;
    this.isOpened = false;
    this.render();
  }

  get template() {
    return `
    <nav class="main-book__menu main-book__menu_closed" data-menu></nav>`;
  }

  initialize() {
    this.initEventListeners();
  }

  initEventListeners() {
    const menuListener = this.article.querySelector(".main-book__menu");

    menuListener.addEventListener("click", (event) => {
      const isAction = event.target.closest("[data-action]");
      if (!!isAction) {
        const id = isAction.dataset.action;
        this.makeAction({ id });
      } else {
        this.openMenu();
      }
    });
    document.addEventListener("menu-outside-click", () => this.closeMenu());
  }

  get actions() {
    return getMenu({
      isBlocked: this.isBlocked,
      hasReadLater: this.hasReadLater,
    });
  }

  getMenuBody() {
    return this.actions
      .map(({ label, id }) => {
        return `
        <li class="main-book__action second-text" id="main-book__action" data-action=${id}>
          ${label}
        </li>`;
      })
      .join("");
  }

  openMenu() {
    this.element.classList.remove("main-book__menu_closed");

    const ulElement = document.createElement("ul");
    ulElement.innerHTML = this.getMenuBody();

    this.element.append(ulElement);
    this.element.classList.add("main-book__menu_opened");
    this.isOpened = true;
  }

  closeMenu() {
    if (this.isOpened) {
      this.element.classList.remove("main-book__menu_opened");
      this.element.firstElementChild.remove();
      this.element.classList.add("main-book__menu_closed");
      this.isOpened = false;
    }
  }

  async makeAction({ id }) {
    this.article.classList.add("blur", "spinner");

    const { action, value } =
      this.actions.find((act) => act.id === Number(id)) || {};

    await action({ id, bookid: this.bookid });

    if (value) {
      const { id, label } = value;
      this[`${id}`] = label;
    }

    this.article.classList.remove("spinner");
    this.closeMenu();
  }

  async waitRendered() {
    await waitForElement(".main-book__menu");
    this.initialize();
  }

  async render() {
    const divElement = document.createElement("div");
    divElement.innerHTML = this.template;

    this.element = divElement.firstElementChild;
    this.waitRendered();
  }
}
