import { createApp } from "vue";
import { _createI18n } from "ChillMainAssets/vuejs/_js/i18n";
import { activityMessages } from "./i18n";
import store from "./store";
import PickTemplate from "ChillDocGeneratorAssets/vuejs/_components/PickTemplate.vue";
import { fetchTemplates } from "ChillDocGeneratorAssets/api/pickTemplate.js";

import App from "./App.vue";

const i18n = _createI18n(activityMessages);

// app for activity

const hasSocialIssues = document.querySelector("#social-issues-acc") !== null;
const hasLocation = document.querySelector("#location") !== null;
const hasPerson = document.querySelector("#add-persons") !== null;

const app = createApp({
  template: `<app
       :hasSocialIssues="hasSocialIssues"
       :hasLocation="hasLocation"
       :hasPerson="hasPerson"
    ></app>`,
  data() {
    return {
      hasSocialIssues,
      hasLocation,
      hasPerson,
    };
  },
})
  .use(store)
  .use(i18n)
  .component("app", App)
  .mount("#activity");

// app for picking template

const i18nGendoc = _createI18n({});

document.querySelectorAll("div[data-docgen-template-picker]").forEach((el) => {
  fetchTemplates(el.dataset.entityClass).then((templates) => {
    const picker = {
      template: `<pick-template :templates="this.templates" :preventDefaultMoveToGenerate="true" @go-to-generate-document="generateDoc"></pick-template>`,
      components: {
        PickTemplate,
      },
      data() {
        return {
          templates: templates,
          entityId: el.dataset.entityId,
        };
      },
      methods: {
        generateDoc({ link, template }) {
          console.log("generateDoc");
          console.log("link", link);
          console.log("template", template);

          let hiddenInput = document.querySelector("input[data-template-id]");

          if (hiddenInput === null) {
            console.error("hidden input not found");
            return;
          }

          hiddenInput.value = template;

          let form = document.querySelector(
            'form[name="chill_activitybundle_activity"',
          );

          if (form === null) {
            console.error("form not found");
            return;
          }

          form.submit();
        },
      },
    };
    createApp(picker).use(i18nGendoc).mount(el);
  });
});
