import { createApp } from "vue";
import App from "./App.vue";
import { _createI18n } from "../_js/i18n";
import { WorkflowAttachment } from "ChillMainAssets/types";
import {
  create_attachment,
  delete_attachment,
  find_attachments_by_workflow,
} from "ChillMainAssets/lib/workflow/attachments";
import { GenericDocForAccompanyingPeriod } from "ChillDocStoreAssets/types/generic_doc";
import ToastPlugin from "vue-toast-notification";
import "vue-toast-notification/dist/theme-bootstrap.css";

window.addEventListener("DOMContentLoaded", () => {
  const attachments = document.querySelectorAll<HTMLDivElement>(
    'div[data-app="workflow_attachments"]',
  );

  attachments.forEach(async (el) => {
    const workflowId = parseInt(el.dataset.entityWorkflowId || "");
    const accompanyingPeriodId = parseInt(
      el.dataset.relatedAccompanyingPeriodId || "",
    );
    const attachments = await find_attachments_by_workflow(workflowId);

    const app = createApp({
      template:
        '<app :workflowId="workflowId" :accompanyingPeriodId="accompanyingPeriodId" :attachments="attachments" @pickGenericDoc="onPickGenericDoc" @removeAttachment="onRemoveAttachment"></app>',
      components: { App },
      data: function () {
        return { workflowId, accompanyingPeriodId, attachments };
      },
      methods: {
        onRemoveAttachment: async function ({
          attachment,
        }: {
          attachment: WorkflowAttachment;
        }): Promise<void> {
          const index = this.$data.attachments.findIndex(
            (el: WorkflowAttachment) => el.id === attachment.id,
          );
          if (-1 === index) {
            console.warn(
              "this attachment is not associated with the workflow",
              attachment,
            );
            this.$toast.error(
              "This attachment is not associated with the workflow",
            );
            return;
          }

          try {
            await delete_attachment(attachment);
          } catch (error) {
            console.error(error);
            this.$toast.error("Error while removing element");
            throw error;
          }
          this.$data.attachments.splice(index, 1);
          this.$toast.success("Pièce jointe supprimée");
        },
        onPickGenericDoc: async function ({
          genericDoc,
        }: {
          genericDoc: GenericDocForAccompanyingPeriod;
        }): Promise<void> {
          console.log("picked generic doc", genericDoc);

          // prevent to create double attachment:
          if (
            -1 !==
            this.$data.attachments.findIndex(
              (el: WorkflowAttachment) =>
                el.genericDoc?.key === genericDoc.key &&
                JSON.stringify(el.genericDoc?.identifiers) ==
                  JSON.stringify(genericDoc.identifiers),
            )
          ) {
            console.warn(
              "this document is already attached to the workflow",
              genericDoc,
            );
            this.$toast.error("Ce document est déjà attaché au workflow");
            return;
          }

          try {
            const attachment = await create_attachment(workflowId, genericDoc);
            this.$data.attachments.push(attachment);
          } catch (error) {
            console.error(error);
            throw error;
          }
        },
      },
    });
    const i18n = _createI18n({});
    app.use(i18n);
    app.use(ToastPlugin);

    app.mount(el);
  });
});
