import { defineStore } from "pinia";
import { http } from "@/serverCom";
import type { ProtocolPrintoutViewModel } from "@/viewmodels/admin/protocolPrintout.models";
import { useProtocolStore } from "./protocol";
import type { AxiosResponse } from "axios";

export const useProtocolPrintoutStore = defineStore("protocolPrintout", {
  state: () => {
    return {
      printout: [] as Array<ProtocolPrintoutViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
      printing: undefined as undefined | "loading" | "success" | "failed",
    };
  },
  actions: {
    fetchProtocolPrintout() {
      const protocolId = useProtocolStore().activeProtocol;
      this.loading = "loading";
      http
        .get(`/admin/protocol/${protocolId}/printouts`)
        .then((result) => {
          this.printout = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchProtocolPrintoutById(printoutId: number): Promise<AxiosResponse<any, any>> {
      const protocolId = useProtocolStore().activeProtocol;
      return http.get(`/admin/protocol/${protocolId}/printout/${printoutId}`, {
        responseType: "blob",
      });
    },
    createProtocolPrintout() {
      this.printing = "loading";
      const protocolId = useProtocolStore().activeProtocol;
      if (protocolId == null) return;
      return http
        .post(`/admin/protocol/${protocolId}/printout`)
        .then((res) => {
          this.fetchProtocolPrintout();
          this.printing = "success";
        })
        .catch((err) => {
          this.printing = "failed";
        })
        .finally(() => {
          setTimeout(() => {
            this.printing = undefined;
          }, 1500);
        });
    },
  },
});
