import { defineStore } from "pinia";
import { http, newEventSource, streamingFetch } from "@/serverCom";
import { useNewsletterStore } from "./newsletter";
import type { AxiosResponse } from "axios";
import type { EventSourcePolyfill } from "event-source-polyfill";
import { useNotificationStore, type NotificationType } from "../../../notification";

export const useNewsletterPrintoutStore = defineStore("newsletterPrintout", {
  state: () => {
    return {
      printout: [] as Array<string>,
      loading: "loading" as "loading" | "fetched" | "failed",
      printing: undefined as undefined | "loading" | "success" | "failed",
      sending: undefined as undefined | "loading" | "success" | "failed",
      sendingPreview: undefined as undefined | "loading" | "success" | "failed",
      pdfSourceMessages: [] as Array<{ kind: string; factor: string; [key: string]: string }>,
      mailSourceMessages: [] as Array<{ kind: string; factor: string; [key: string]: string }>,
      pdfPrintingAbort: undefined as undefined | AbortController,
      mailSendingAbort: undefined as undefined | AbortController,
    };
  },
  actions: {
    fetchNewsletterPrintout() {
      const newsletterId = useNewsletterStore().activeNewsletter;
      this.loading = "loading";
      http
        .get(`/admin/newsletter/${newsletterId}/printouts`)
        .then((result) => {
          this.printout = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchNewsletterPrintoutById(printout: string): Promise<AxiosResponse<any, any>> {
      const newsletterId = useNewsletterStore().activeNewsletter;
      return http.get(`/admin/newsletter/${newsletterId}/printout/${printout}`, {
        responseType: "blob",
      });
    },
    fetchNewsletterPrintoutPreview(): Promise<AxiosResponse<any, any>> {
      const newsletterId = useNewsletterStore().activeNewsletter;
      return http.get(`/admin/newsletter/${newsletterId}/printoutpreview`, {
        responseType: "blob",
      });
    },
    createNewsletterMailPreview() {
      this.sendingPreview = "loading";
      const newsletterId = useNewsletterStore().activeNewsletter;
      if (newsletterId == null) return;
      return http
        .post(`/admin/newsletter/${newsletterId}/mailpreview`)
        .then((res) => {
          this.sendingPreview = "success";
        })
        .catch((err) => {
          this.sendingPreview = "failed";
        })
        .finally(() => {
          setTimeout(() => {
            this.sendingPreview = undefined;
          }, 1500);
        });
    },
    createNewsletterPrintout() {
      this.subscribePdfPrintingProgress();
      this.printing = "loading";
      const newsletterId = useNewsletterStore().activeNewsletter;
      if (newsletterId == null) return;
      return http
        .post(`/admin/newsletter/${newsletterId}/printout`)
        .then((res) => {
          this.fetchNewsletterPrintout();
          this.printing = "success";
        })
        .catch((err) => {
          this.printing = "failed";
        })
        .finally(() => {
          setTimeout(() => {
            this.printing = undefined;
            this.pdfPrintingAbort?.abort();
          }, 1500);
        });
    },
    createNewsletterSend() {
      this.subscribeMailSendingProgress();
      this.sending = "loading";
      const newsletterId = useNewsletterStore().activeNewsletter;
      if (newsletterId == null) return;
      return http
        .post(`/admin/newsletter/${newsletterId}/send`)
        .then((res) => {
          this.sending = "success";
        })
        .catch((err) => {
          this.sending = "failed";
        })
        .finally(() => {
          setTimeout(() => {
            this.sending = undefined;
            this.mailSendingAbort?.abort();
          }, 1500);
        });
    },
    async subscribePdfPrintingProgress() {
      this.pdfSourceMessages = [];
      const newsletterId = useNewsletterStore().activeNewsletter;
      const notificationStore = useNotificationStore();
      this.pdfPrintingAbort = new AbortController();
      for await (let chunk of streamingFetch(
        `/admin/newsletter/${newsletterId}/printoutprogress`,
        this.pdfPrintingAbort
      )) {
        chunk.split("//").forEach((r) => {
          if (r.trim() != "") {
            let data = JSON.parse(r);
            this.pdfSourceMessages.push(data);
            let type: NotificationType = "info";
            let timeout = undefined;
            if (data.factor == "failed") {
              type = "error";
              timeout = 0;
            }
            notificationStore.push(`Druck: ${data.iteration}/${data.total}`, `${data.msg}`, type, timeout);
          }
        });
        this.fetchNewsletterPrintout();
      }
    },
    async subscribeMailSendingProgress() {
      this.mailSourceMessages = [];
      const newsletterId = useNewsletterStore().activeNewsletter;
      const notificationStore = useNotificationStore();
      this.mailSendingAbort = new AbortController();
      for await (let chunk of streamingFetch(`/admin/newsletter/${newsletterId}/sendprogress`, this.mailSendingAbort)) {
        chunk.split("//").forEach((r) => {
          if (r.trim() != "") {
            let data = JSON.parse(r);
            this.mailSourceMessages.push(data);
            let type: NotificationType = "info";
            let timeout = undefined;
            if (data.factor == "failed") {
              type = "error";
              timeout = 0;
            }
            notificationStore.push(`Mailversand: ${data.iteration}/${data.total}`, `${data.msg}`, type, timeout);
          }
        });
      }
    },
  },
});
