import { DomList } from "./dom-list.js";
import { addEventToElement, setText } from "./dom-utils.js";
import { awaitEvent, emitEvent, listenTo } from "./events.js";
import { registerLoadCallback } from "./main.js";
import { recall, save } from "./storage.js";

registerLoadCallback(() => {
  welcomeDialog();
  listenTo("dialogs:welcome", () => welcomeDialog(true));
  listenTo("fileLoad:chooseDesign", designChoiceDialog);
  listenTo("fileSave:nameDesign", designNameDialog);
  listenTo("error:user", errorDialog);
});

function initializeDialog(dialogName, endEvent, { emptyValue, onDismiss } = {}) {
  const dialog = document.querySelector(`[data-dialog="${dialogName}"]`);

  const dismiss = (data) => {
    dialog.classList.add("hidden");
    console.log("dimiss > emit", data);
    emitEvent(endEvent, data);
    if (onDismiss) {
      onDismiss();
    }
  }

  addEventToElement(
      "dialog-action", "cancel", "click",
      () => dismiss(emptyValue),
      { element: dialog },
  );
  dialog.addEventListener("click", e => {
    if (e.target !== e.currentTarget) return;
    dismiss(emptyValue);
  });

  queueMicrotask(() => {
    dialog.classList.remove("hidden");
  });

  return {
    dialog,
    dismiss,
  };
}

function welcomeDialog(force = false) {
  if (recall("hasSeenWelcome", false) && !force) {
    return;
  }

  initializeDialog("welcome", "welcome:close", {
    onDismiss: () => {
      save("hasSeenWelcome", true);
    }
  });
}

function designChoiceDialog(e) {
  const {
    dialog, dismiss
  } = initializeDialog("fileLoad:chooseDesign", "fileLoad:chooseDesign:choice", -1);

  const list = new DomList(dialog.querySelector(":scope > section > main"));
  list.clear();

  for (const designIndex in e.detail.designs) {
    const design = e.detail.designs[designIndex];
    const button = list.makeItem();
    setText("Name", design.modules["plannerator:metadata"].Name, { element: button });
    setText("Author", design.modules["plannerator:metadata"].Author, { element: button });
    button.addEventListener("click", () => dismiss(designIndex));
    list.addItem(button);
  }
}

function designNameDialog() {
  const {
    dismiss
  } = initializeDialog(
      "fileSave:nameDesign",
      "fileSave:nameDesign:named",
      {
        emptyValue: null
      }
  );

  awaitEvent("fileSave:nameDesign:submit").then(e => {
    dismiss(new FormData(e.detail.target).get("name"));
  });
}

function errorDialog(e) {
  const { dialog } = initializeDialog("error:user", "error:dialog:close");
  dialog.querySelectorAll('[data-text="error"]').forEach(elem => elem.innerText = e.detail);
}
