import { createApp } from "vue";
import PickEntity from "ChillMainAssets/vuejs/PickEntity/PickEntity.vue";
import { _createI18n } from "ChillMainAssets/vuejs/_js/i18n";
import { appMessages } from "ChillMainAssets/vuejs/PickEntity/i18n";

const i18n = _createI18n(appMessages);

let appsOnPage = new Map();
let appsPerInput = new Map();

function loadDynamicPicker(element) {
  let apps = element.querySelectorAll('[data-module="pick-dynamic"]');

  apps.forEach(function (el) {
    let suggested;
    let as_id;
    let submit_on_adding_new_entity;
    let label;
    let isCurrentUserPicker;
    const isMultiple = parseInt(el.dataset.multiple) === 1,
      uniqId = el.dataset.uniqid,
      input = element.querySelector(
        '[data-input-uniqid="' + el.dataset.uniqid + '"]',
      ),
      // the "picked" will always be an array, even if multiple is false
      picked = isMultiple
        ? JSON.parse(input.value)
        : input.value === "[]" || input.value === ""
          ? null
          : [JSON.parse(input.value)];
    suggested = JSON.parse(el.dataset.suggested);
    as_id = parseInt(el.dataset.asId) === 1;
    submit_on_adding_new_entity =
      parseInt(el.dataset.submitOnAddingNewEntity) === 1;
    label = el.dataset.label;
    isCurrentUserPicker = uniqId.startsWith("pick_user_or_me_dyn");

    if (!isMultiple) {
      if (input.value === "[]") {
        input.value = null;
      }
    }

    const app = createApp({
      template:
        "<pick-entity " +
        ':multiple="multiple" ' +
        ':types="types" ' +
        ':picked="picked" ' +
        ':uniqid="uniqid" ' +
        ':suggested="notPickedSuggested" ' +
        ':label="label" ' +
        ':isCurrentUserPicker="isCurrentUserPicker" ' +
        '@addNewEntity="addNewEntity" ' +
        '@removeEntity="removeEntity" ' +
        '@addNewEntityProcessEnded="addNewEntityProcessEnded"' +
        "></pick-entity>",
      components: {
        PickEntity,
      },
      data() {
        return {
          multiple: isMultiple,
          types: JSON.parse(el.dataset.types),
          picked: picked === null ? [] : picked,
          uniqid: el.dataset.uniqid,
          suggested,
          as_id,
          submit_on_adding_new_entity,
          label,
          isCurrentUserPicker,
        };
      },
      computed: {
        notPickedSuggested() {
          const pickedIds = new Set();
          for (const p of this.picked) {
            pickedIds.add(`${p.type}${p.id}`);
          }
          return this.suggested.filter(
            (e) => !pickedIds.has(`${e.type}${e.id}`),
          );
        },
      },
      methods: {
        addNewEntity({ entity }) {
          if (this.multiple) {
            if (
              !this.picked.some((el) => {
                return el.type === entity.type && el.id === entity.id;
              })
            ) {
              this.picked.push(entity);
              if (!as_id) {
                input.value = JSON.stringify(this.picked);
              } else {
                const ids = this.picked.map((el) => el.id);
                input.value = ids.join(",");
              }
              console.log(this.picked);
              // console.log(entity);
            }
          } else {
            if (
              !this.picked.some((el) => {
                return el.type === entity.type && el.id === entity.id;
              })
            ) {
              this.picked.splice(0, this.picked.length);
              this.picked.push(entity);
              if (!as_id) {
                input.value = JSON.stringify(this.picked[0]);
              } else {
                input.value = this.picked.map((el) => el.id);
              }
            }
          }
        },
        addNewEntityProcessEnded() {
          if (this.submit_on_adding_new_entity) {
            input.form.submit();
          }
        },
        removeEntity({ entity }) {
          if (
            -1 ===
              this.suggested.findIndex(
                (e) => e.type === entity.type && e.id === entity.id,
              ) &&
            "me" !== entity
          ) {
            this.suggested.push(entity);
          }
          this.picked = this.picked.filter(
            (e) => !(e.type === entity.type && e.id === entity.id),
          );
          if (this.multiple) {
            input.value = JSON.stringify(this.picked);
          } else {
            input.value = "";
          }
        },
      },
    })
      .use(i18n)
      .mount(el);

    appsOnPage.set(uniqId, app);
    appsPerInput.set(input.name, app);
  });
}

document.addEventListener("show-hide-show", function (e) {
  loadDynamicPicker(e.detail.container);
});

document.addEventListener("show-hide-hide", function (e) {
  console.log("hiding event caught");
  e.detail.container
    .querySelectorAll('[data-module="pick-dynamic"]')
    .forEach((el) => {
      let uniqId = el.dataset.uniqid;
      if (appsOnPage.has(uniqId)) {
        appsOnPage.get(uniqId).unmount();
        appsOnPage.delete(uniqId);
      }
    });
});

document.addEventListener("pick-entity-type-action", function (e) {
  console.log("pick entity event", e);
  if (!appsPerInput.has(e.detail.name)) {
    console.error("no app with this name");
    return;
  }
  const app = appsPerInput.get(e.detail.name);
  if (e.detail.action === "add") {
    app.addNewEntity(e.detail.entity);
  } else if (e.detail.action === "remove") {
    app.removeEntity(e.detail.entity);
  } else {
    console.error("action not supported: " + e.detail.action);
  }
});

document.addEventListener("DOMContentLoaded", function () {
  loadDynamicPicker(document);
});

window.loadDynamicPicker = loadDynamicPicker;
