import { defineStore } from "pinia";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";
import type { ProtocolVotingViewModel, SyncProtocolVotingViewModel } from "@/viewmodels/admin/protocolVoting.models";
import { useProtocolStore } from "./protocol";
import cloneDeep from "lodash.clonedeep";
import isEqual from "lodash.isequal";
import differenceWith from "lodash.differencewith";

export const useProtocolVotingStore = defineStore("protocolVoting", {
  state: () => {
    return {
      voting: [] as Array<ProtocolVotingViewModel>,
      origin: [] as Array<ProtocolVotingViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
      syncingProtocolVoting: "synced" as "synced" | "syncing" | "detectedChanges" | "failed",
    };
  },
  getters: {
    detectedChangeProtocolVoting: (state) =>
      !isEqual(state.origin, state.voting) && state.syncingProtocolVoting != "syncing",
  },
  actions: {
    setProtocolVotingSyncingState(state: "synced" | "syncing" | "detectedChanges" | "failed") {
      this.syncingProtocolVoting = state;
    },
    fetchProtocolVoting() {
      this.loading = "loading";
      this.fetchProtocolVotingPromise()
        .then((result) => {
          this.origin = result.data;
          this.voting = cloneDeep(this.origin);
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchProtocolVotingPromise() {
      const protocolId = useProtocolStore().activeProtocol;
      return http.get(`/admin/protocol/${protocolId}/votings`);
    },
    createProtocolVoting() {
      const protocolId = useProtocolStore().activeProtocol;
      if (protocolId == null) return;
      return http
        .post(`/admin/protocol/${protocolId}/voting`)
        .then((res) => {
          this.voting.push({
            id: Number(res.data),
            topic: "",
            context: "",
            favour: 0,
            abstain: 0,
            against: 0,
            protocolId: Number(protocolId),
          });
        })
        .catch((err) => {});
    },
    async synchronizeActiveProtocolVoting() {
      this.syncingProtocolVoting = "syncing";
      const protocolId = useProtocolStore().activeProtocol;

      await http
        .patch(`/admin/protocol/${protocolId}/synchronize/votings`, {
          votings: differenceWith(this.voting, this.origin, isEqual),
        })
        .then((res) => {
          this.syncingProtocolVoting = "synced";
        })
        .catch((err) => {
          this.syncingProtocolVoting = "failed";
        });
      this.fetchProtocolVotingPromise()
        .then((res) => {
          this.origin = res.data;
          if (this.detectedChangeProtocolVoting) this.syncingProtocolVoting = "detectedChanges";
        })
        .catch((err) => {});
    },
  },
});
