import { defineStore } from "pinia";
import { http } from "@/serverCom";
import type { NewsletterDatesViewModel, SyncNewsletterDatesViewModel } from "@/viewmodels/admin/newsletterDates.models";
import { useNewsletterStore } from "./newsletter";
import cloneDeep from "lodash.clonedeep";
import isEqual from "lodash.isequal";
import differenceWith from "lodash.differencewith";

export const useNewsletterDatesStore = defineStore("newsletterDates", {
  state: () => {
    return {
      dates: [] as Array<NewsletterDatesViewModel>,
      origin: [] as Array<NewsletterDatesViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
      syncingNewsletterDates: "synced" as "synced" | "syncing" | "detectedChanges" | "failed",
    };
  },
  getters: {
    detectedChangeNewsletterDates: (state) =>
      !isEqual(
        state.origin.sort(
          (a: NewsletterDatesViewModel, b: NewsletterDatesViewModel) =>
            new Date(a.calendar.starttime).getTime() - new Date(b.calendar.starttime).getTime()
        ),
        state.dates.sort(
          (a: NewsletterDatesViewModel, b: NewsletterDatesViewModel) =>
            new Date(a.calendar.starttime).getTime() - new Date(b.calendar.starttime).getTime()
        )
      ) && state.syncingNewsletterDates != "syncing",
  },
  actions: {
    setNewsletterDatesSyncingState(state: "synced" | "syncing" | "detectedChanges" | "failed") {
      this.syncingNewsletterDates = state;
    },
    fetchNewsletterDates() {
      this.loading = "loading";
      this.fetchNewsletterDatesPromise()
        .then((result) => {
          this.origin = result.data;
          this.dates = cloneDeep(this.origin);
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchNewsletterDatesPromise() {
      const newsletterId = useNewsletterStore().activeNewsletter;
      return http.get(`/admin/newsletter/${newsletterId}/dates`);
    },
    async synchronizeActiveNewsletterDates() {
      this.syncingNewsletterDates = "syncing";
      const newsletterId = useNewsletterStore().activeNewsletter;

      await http
        .patch(`/admin/newsletter/${newsletterId}/synchronize/dates`, {
          dates: this.dates,
        })
        .then((res) => {
          this.syncingNewsletterDates = "synced";
        })
        .catch((err) => {
          this.syncingNewsletterDates = "failed";
        });
      this.fetchNewsletterDatesPromise()
        .then((res) => {
          this.origin = res.data;
          if (this.detectedChangeNewsletterDates) this.syncingNewsletterDates = "detectedChanges";
        })
        .catch((err) => {});
    },
  },
});
