import { _createI18n } from "ChillMainAssets/vuejs/_js/i18n";
import DocumentActionButtonsGroup from "../../vuejs/DocumentActionButtonsGroup.vue";
import { createApp } from "vue";
import { StoredObject, StoredObjectStatusChange } from "../../types";
import { is_object_ready } from "../../vuejs/StoredObjectButton/helpers";
import ToastPlugin from "vue-toast-notification";

const i18n = _createI18n({});

window.addEventListener("DOMContentLoaded", function (e) {
  document
    .querySelectorAll<HTMLDivElement>("div[data-download-buttons]")
    .forEach((el) => {
      const app = createApp({
        components: { DocumentActionButtonsGroup },
        data() {
          const datasets = el.dataset as {
            filename: string;
            canEdit: string;
            storedObject: string;
            buttonSmall: string;
            davLink: string;
            davLinkExpiration: string;
          };

          const storedObject = JSON.parse(
              datasets.storedObject,
            ) as StoredObject,
            filename = datasets.filename,
            canEdit = datasets.canEdit === "1",
            small = datasets.buttonSmall === "1",
            davLink =
              "davLink" in datasets && datasets.davLink !== ""
                ? datasets.davLink
                : null,
            davLinkExpiration =
              "davLinkExpiration" in datasets
                ? Number.parseInt(datasets.davLinkExpiration)
                : null;
          return {
            storedObject,
            filename,
            canEdit,
            small,
            davLink,
            davLinkExpiration,
          };
        },
        template:
          '<document-action-buttons-group :can-edit="canEdit" :filename="filename" :stored-object="storedObject" :small="small" :dav-link="davLink" :dav-link-expiration="davLinkExpiration" @on-stored-object-status-change="onStoredObjectStatusChange"></document-action-buttons-group>',
        methods: {
          onStoredObjectStatusChange: function (
            newStatus: StoredObjectStatusChange,
          ): void {
            this.$data.storedObject.status = newStatus.status;
            this.$data.storedObject.filename = newStatus.filename;
            this.$data.storedObject.type = newStatus.type;

            // remove eventual div which inform pending status
            document
              .querySelectorAll(
                `[data-docgen-is-pending="${this.$data.storedObject.id}"]`,
              )
              .forEach(function (el) {
                el.remove();
              });
          },
        },
      });

      app.use(i18n).use(ToastPlugin).mount(el);
    });
});
