import { useTaehuiStore } from "@/state/Stores";
import { wwwAPI } from "@/utilities/wwwAPI";
import { useMutation } from "@tanstack/react-query";
import { getMillis } from "taehui-lib/date";

export default function usePostFile() {
  const { totem } = useTaehuiStore();

  return useMutation({
    mutationFn: async ({
      file,
      textView,
    }: {
      file: File;
      textView: HTMLTextAreaElement;
    }) => {
      const form = new FormData();
      form.append("data", file);
      const {
        status,
        data: { fileName },
      } = await wwwAPI.post("/file", form, {
        headers: {
          millis: getMillis(),
          totem,
        },
      });
      if (status === 201) {
        const { selectionStart, value } = textView;
        const textBefore = value.substring(0, selectionStart);
        const textLater = value.substring(selectionStart, value.length);
        if (fileName.match(/^.*\.(bmp|gif|jpeg|jpg|png|webp)$/i)) {
          return `${textBefore}<img src=${fileName}>${textLater}`;
        } else if (
          fileName.match(
            /^.*\.(aif|aiff|asf|flac|m4a|mid|midi|mp2|mp3|ogg|opus|raw|wav|wma)$/i,
          )
        ) {
          return `${textBefore}<audio src="${fileName}" controls></audio>${textLater}`;
        } else if (
          fileName.match(/^.*\.(avi|flv|m1v|mkv|mov|mp4|mpeg|mpg|webm|wmv)$/i)
        ) {
          return `${textBefore}<video src="${fileName}" controls></video>${textLater}`;
        } else {
          return `${textBefore}<a href="${fileName}">${file.name}</a>${textLater}`;
        }
      }
    },
  });
}
