import { findPlaceholder, uploadPlaceholder } from "./uploadPlaceholder";
import { toastrMessage } from "./exec-toastr";
import { requestUploadFile1, RetSeek } from "../../req-upload-file";
import { getKunImageUrl } from "../../../kun-chat-message/kun-chat-message";


const uploadFile = async (file: File): Promise<RetSeek> => {
  const formData = new FormData();
  formData.set("file", file);
  return requestUploadFile1(formData);
};

const insertFiles = async (view, event, pos, files): Promise<void> => {
  // filter to only include image files
  const images = files.filter((file) => /image/i.test(file.type));
  if (images.length === 0) return;

  // event going any further up the stack
  event.preventDefault();

  // let the user know we're starting to process the images

  const { schema } = view.state;

  // we'll use this to track of how many images have succeeded or failed
  let complete = 0;

  // the user might have dropped multiple images at once, we need to loop
  for (const file of images) {
    // Use an object to act as the ID for this upload, clever.
    const id = {};

    const { tr } = view.state;

    // insert a placeholder at this position
    tr.setMeta(uploadPlaceholder, {
      add: { id, file, pos },
    });
    view.dispatch(tr);

    // start uploading the image file to the server. Using "then" syntax
    // to allow all placeholders to be entered at once with the uploads
    // happening in the background in parallel.
    uploadFile(file)
      .then((src) => {
        const pos = findPlaceholder(view.state, id);

        // if the content around the placeholder has been deleted
        // then forget about inserting this image
        if (pos === null) return;

        // otherwise, insert it at the placeholder's position, and remove
        // the placeholder itself
        const transaction = view.state.tr
          .replaceWith(pos, pos, schema.nodes.image.create({ src: getKunImageUrl(src.msg) }))
          .setMeta(uploadPlaceholder, { remove: { id } });

        view.dispatch(transaction);
      })
      .catch((error) => {
        console.error(error);

        // cleanup the placeholder if there is a failure
        const transaction = view.state.tr.setMeta(uploadPlaceholder, {
          remove: { id },
        });
        view.dispatch(transaction);
        toastrMessage(String(error));
      }).then(() => {
        complete++;
      });
  }
};

export default insertFiles;
