import { CollectionEventPayload } from "../../../../../ChillMainBundle/Resources/public/module/collection";
import { createApp } from "vue";
import DropFileWidget from "../../vuejs/DropFileWidget/DropFileWidget.vue";
import { StoredObject, StoredObjectVersion } from "../../types";
import { _createI18n } from "../../../../../ChillMainBundle/Resources/public/vuejs/_js/i18n";
const i18n = _createI18n({});

const startApp = (
  divElement: HTMLDivElement,
  collectionEntry: null | HTMLLIElement,
): void => {
  console.log("app started", divElement);

  const inputTitle = collectionEntry?.querySelector("input[type='text']");

  const input_stored_object: HTMLInputElement | null = divElement.querySelector(
    "input[data-stored-object]",
  );
  if (null === input_stored_object) {
    throw new Error("input to stored object not found");
  }

  let existingDoc: StoredObject | null = null;
  if (input_stored_object.value !== "") {
    existingDoc = JSON.parse(input_stored_object.value);
  }
  const app_container = document.createElement("div");
  divElement.appendChild(app_container);

  const app = createApp({
    template:
      '<drop-file-widget :existingDoc="this.$data.existingDoc" :allowRemove="true" @addDocument="this.addDocument" @removeDocument="removeDocument"></drop-file-widget>',
    data() {
      return {
        existingDoc: existingDoc,
        inputTitle: inputTitle,
      };
    },
    components: {
      DropFileWidget,
    },
    methods: {
      addDocument: function ({
        stored_object,
        stored_object_version,
        file_name,
      }: {
        stored_object: StoredObject;
        stored_object_version: StoredObjectVersion;
        file_name: string;
      }): void {
        stored_object.title = file_name;
        console.log("object added", stored_object);
        console.log("version added", stored_object_version);
        this.$data.existingDoc = stored_object;
        this.$data.existingDoc.currentVersion = stored_object_version;
        input_stored_object.value = JSON.stringify(this.$data.existingDoc);
        if (this.$data.inputTitle) {
          if (!this.$data.inputTitle?.value) {
            this.$data.inputTitle.value = file_name;
          }
        }
      },
      removeDocument: function (object: StoredObject): void {
        console.log("catch remove document", object);
        input_stored_object.value = "";
        this.$data.existingDoc = undefined;
        console.log("collectionEntry", collectionEntry);

        if (null !== collectionEntry) {
          console.log("will remove collection");
          collectionEntry.remove();
        }
      },
    },
  });

  app.use(i18n).mount(app_container);
};
window.addEventListener("collection-add-entry", ((
  e: CustomEvent<CollectionEventPayload>,
) => {
  const detail = e.detail;
  const divElement: null | HTMLDivElement = detail.entry.querySelector(
    "div[data-stored-object]",
  );

  if (null === divElement) {
    throw new Error("div[data-stored-object] not found");
  }

  startApp(divElement, detail.entry);
}) as EventListener);

window.addEventListener("DOMContentLoaded", () => {
  const upload_inputs: NodeListOf<HTMLDivElement> = document.querySelectorAll(
    "div[data-stored-object]",
  );

  upload_inputs.forEach((input: HTMLDivElement): void => {
    // test for a parent to check if this is a collection entry
    let collectionEntry: null | HTMLLIElement = null;
    const parent = input.parentElement;
    console.log("parent", parent);
    if (null !== parent) {
      const grandParent = parent.parentElement;
      console.log("grandParent", grandParent);
      if (null !== grandParent) {
        if (
          grandParent.tagName.toLowerCase() === "li" &&
          grandParent.classList.contains("entry")
        ) {
          collectionEntry = grandParent as HTMLLIElement;
        }
      }
    }
    startApp(input, collectionEntry);
  });
});

export {};
