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

export const useProtocolPresenceStore = defineStore("protocolPresence", {
  state: () => {
    return {
      presence: [] as Array<number>,
      origin: [] as Array<number>,
      loading: "loading" as "loading" | "fetched" | "failed",
      syncingProtocolPresence: "synced" as "synced" | "syncing" | "detectedChanges" | "failed",
    };
  },
  getters: {
    detectedChangeProtocolPresence: (state) =>
      !isEqual(state.origin, state.presence) && 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.map((d: ProtocolPresenceViewModel) => d.memberId);
          this.presence = cloneDeep(this.origin);
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchProtocolPresencePromise() {
      const protocolId = useProtocolStore().activeProtocol;
      return http.get(`/admin/protocol/${protocolId}/presence`);
    },
    async synchronizeActiveProtocolPresence() {
      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.map((d: ProtocolPresenceViewModel) => d.memberId);
          if (this.detectedChangeProtocolPresence) this.syncingProtocolPresence = "detectedChanges";
        })
        .catch((err) => {});
    },
  },
});
