import { defineStore } from "pinia";
import { http } from "@/serverCom";
import type { ProtocolAgendaViewModel, SyncProtocolAgendaViewModel } from "@/viewmodels/admin/club/protocol/protocolAgenda.models";
import { useProtocolStore } from "./protocol";
import cloneDeep from "lodash.clonedeep";
import isEqual from "lodash.isequal";
import differenceWith from "lodash.differencewith";

export const useProtocolAgendaStore = defineStore("protocolAgenda", {
  state: () => {
    return {
      agenda: [] as Array<ProtocolAgendaViewModel>,
      origin: [] as Array<ProtocolAgendaViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
      syncingProtocolAgenda: "synced" as "synced" | "syncing" | "detectedChanges" | "failed",
    };
  },
  getters: {
    detectedChangeProtocolAgenda: (state) =>
      !isEqual(state.origin, state.agenda) && state.syncingProtocolAgenda != "syncing",
  },
  actions: {
    setProtocolAgendaSyncingState(state: "synced" | "syncing" | "detectedChanges" | "failed") {
      this.syncingProtocolAgenda = state;
    },
    fetchProtocolAgenda() {
      this.loading = "loading";
      this.fetchProtocolAgendaPromise()
        .then((result) => {
          this.origin = result.data;
          this.agenda = cloneDeep(this.origin);
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchProtocolAgendaPromise() {
      const protocolId = useProtocolStore().activeProtocol;
      return http.get(`/admin/protocol/${protocolId}/agenda`);
    },
    createProtocolAgenda() {
      const protocolId = useProtocolStore().activeProtocol;
      if (protocolId == null) return;
      return http
        .post(`/admin/protocol/${protocolId}/agenda`)
        .then((res) => {
          this.agenda.push({
            id: Number(res.data),
            topic: "",
            context: "",
            protocolId: Number(protocolId),
          });
        })
        .catch((err) => {});
    },
    async synchronizeActiveProtocolAgenda() {
      this.syncingProtocolAgenda = "syncing";
      const protocolId = useProtocolStore().activeProtocol;

      await http
        .patch(`/admin/protocol/${protocolId}/synchronize/agenda`, {
          agenda: differenceWith(this.agenda, this.origin, isEqual),
        })
        .then((res) => {
          this.syncingProtocolAgenda = "synced";
        })
        .catch((err) => {
          this.syncingProtocolAgenda = "failed";
        });
      this.fetchProtocolAgendaPromise()
        .then((res) => {
          this.origin = res.data;
          if (this.detectedChangeProtocolAgenda) this.syncingProtocolAgenda = "detectedChanges";
        })
        .catch((err) => {});
    },
  },
});