import { defineStore } from "pinia";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";
import type {
  ProtocolPresenceViewModel,
  SyncProtocolPresenceViewModel,
} from "@/viewmodels/admin/club/protocol/protocolPresence.models";
import { useProtocolStore } from "./protocol";
import cloneDeep from "lodash.clonedeep";
import isEqual from "lodash.isequal";

export const useProtocolPresenceStore = defineStore("protocolPresence", {
  state: () => {
    return {
      initialized: false as boolean,
      presence: [] as Array<ProtocolPresenceViewModel>,
      origin: [] as Array<ProtocolPresenceViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
      syncingProtocolPresence: "synced" as "synced" | "syncing" | "detectedChanges" | "failed",
    };
  },
  getters: {
    detectedChangeProtocolPresence: (state) =>
      !isEqual(
        state.origin.sort((a: ProtocolPresenceViewModel, b: ProtocolPresenceViewModel) => a.memberId - b.memberId),
        state.presence.sort((a: ProtocolPresenceViewModel, b: ProtocolPresenceViewModel) => a.memberId - b.memberId)
      ) && state.syncingProtocolPresence != "syncing",
  },
  actions: {
    setProtocolPresenceSyncingState(state: "synced" | "syncing" | "detectedChanges" | "failed") {
      this.syncingProtocolPresence = state;
    },
    fetchProtocolPresence() {
      this.loading = "loading";
      this.fetchProtocolPresencePromise()
        .then((result) => {
          this.origin = result.data;
          this.presence = cloneDeep(this.origin);
          this.initialized = true;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchProtocolPresencePromise() {
      const protocolId = useProtocolStore().activeProtocol;
      return http.get(`/admin/protocol/${protocolId}/presence`);
    },
    async synchronizeActiveProtocolPresence() {
      if (!this.initialized) return;

      this.syncingProtocolPresence = "syncing";
      const protocolId = useProtocolStore().activeProtocol;

      await http
        .put(`/admin/protocol/${protocolId}/synchronize/presence`, {
          presence: this.presence,
        })
        .then((res) => {
          this.syncingProtocolPresence = "synced";
        })
        .catch((err) => {
          this.syncingProtocolPresence = "failed";
        });
      this.fetchProtocolPresencePromise()
        .then((result) => {
          this.origin = result.data;
          if (this.detectedChangeProtocolPresence) this.syncingProtocolPresence = "detectedChanges";
        })
        .catch((err) => {});
    },
  },
});
