import { Node, Plugin } from "../../tiptap";
import { markPasteRule, nodeInputRule } from "../../commands";
import { requestUploadFile1 } from "../../req-upload-file";
import { getKunImageUrl } from "../../../kun-chat-message/kun-chat-message";
import insertFiles from "../extensions/insertFiles";
import {uploadPlaceholder} from "../extensions/uploadPlaceholder";

/**
 * Matches following attributes in Markdown-typed image: [, alt, src, title]
 *
 * Example:
 * ![Lorem](image.jpg) -> [, "Lorem", "image.jpg"]
 * ![](image.jpg "Ipsum") -> [, "", "image.jpg", "Ipsum"]
 * ![Lorem](image.jpg "Ipsum") -> [, "Lorem", "image.jpg", "Ipsum"]
 */
const IMAGE_INPUT_REGEX = /!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\)/;

export default class Image extends Node {
  get name() {
    return "image";
  }

  get schema() {
    return {
      inline: true,
      attrs: {
        src: {},
        alt: {
          default: null,
        },
        title: {
          default: null,
        },
      },
      group: "inline",
      draggable: true,
      parseDOM: [
        {
          tag: "img[src]",
          getAttrs: (dom) => ({
            src: dom.getAttribute("src"),
            title: dom.getAttribute("title"),
            alt: dom.getAttribute("alt"),
          }),
        },
      ],
      toDOM: (node) => ["img", node.attrs],
    };
  }

  commands({ type }) {
    return (attrs) => (state, dispatch) => {
      console.log("image type", type);
      const { selection } = state;
      const position = selection.$cursor ? selection.$cursor.pos : selection.$to.pos;
      const node = type.create(attrs);
      const transaction = state.tr.insert(position, node);
      dispatch(transaction);
    };
  }

  inputRules({ type }) {
    return [
      nodeInputRule(IMAGE_INPUT_REGEX, type, (match) => {
        const [, alt, src, title] = match;
        return {
          src,
          alt,
          title,
        };
      }),
    ];
  }

  get plugins() {
    return [
      uploadPlaceholder,
      // uploadPlugin;
      new Plugin({
        props: {
          handleDOMEvents: {
            paste: async (view, event) => {
              console.log("paste");
              const { items } = event.clipboardData || event.originalEvent.clipboardData;
              console.log("items.lenght", items);
              if (items != null) {
                if (items[0] != null) {
                  items[0].getAsString((s) => {
                    console.log("r", s);
                  });
                }
                if (items[1] != null) {
                  items[1].getAsString((s) => {
                    console.log("r", s);
                  });
                }
                console.log("item", items[0]);
                console.log("item1", items[1]);
                const idUploadImage = items[1].kind === "file" && (/image/.test(items[1].type));
                if (idUploadImage) {
                  const { tr } = view.state;
                  if (!tr.selection.empty) {
                    tr.deleteSelection();
                  }
                  const pos = tr.selection.from;
                  event.preventDefault();

                  const files = Array.prototype.slice
                    .call(items)
                    .map((dt) => dt.getAsFile())
                    .filter((file) => file);
                  await insertFiles(view, event, pos, files);
                  return true;
                  // for (let idex = 0; idex < items.length;) {
                  //   idex += 1;
                  //   const { schema } = view.state;
                  //   const item = items[idex];
                  //   if (item != null && item.kind === "file" && /image/.test(item.type)) {
                  //     const image = item.getAsFile();
                  //     if (!image) {
                  //       return;
                  //     }
                  //     const formData = new FormData();
                  //     formData.append("file", image);
                  //     const r = await requestUploadFile1(formData);
                  //     const node = schema.nodes.image.create({
                  //       src: getKunImageUrl(r.msg),
                  //     });
                  //     const transaction = view.state.tr.replaceSelectionWith(node);
                  //     view.dispatch(transaction);
                  //   }
                  // }
                }
              }
            },
            drop(view, event) {
              console.log("drop");
              const hasFiles = event.dataTransfer
              && event.dataTransfer.files
              && event.dataTransfer.files.length;

              if (!hasFiles) {
                return;
              }

              const images = Array
                .from(event.dataTransfer.files)
                .filter((file) => (/image/i).test(file.type));

              if (images.length === 0) {
                return;
              }

              console.log("xxxxxxxxxxxx  images", images);
              event.preventDefault();

              const { schema } = view.state;
              const coordinates = view.posAtCoords({ left: event.clientX, top: event.clientY });

              images.forEach((image) => {
                const reader = new FileReader();
                console.log("read image");

                reader.onload = (readerEvent) => {
                  const node = schema.nodes.image.create({
                    src: readerEvent.target.result,
                  });
                  const transaction = view.state.tr.insert(coordinates.pos, node);
                  view.dispatch(transaction);
                };
                reader.readAsDataURL(image);
              });
            },
          },
        },
      }),
    ];
  }

  // pasteRules({ type }) {
  //   return [
  //     markPasteRule(/img/g, "h1", {
  //
  //     }),
  //   ];
  // }
}
