import {
  Component, h, useEvent, useRef,
} from "atomico";
import html2canvas from "@crcastle/html2canvas";
import style from "./kun-canvas-upload.scss";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";
import { requestUploadFile1 } from "../kun-editor/req-upload-file";

const KunCanvasUpload: Component = ({ children, message }) => {
  const canvasRef = useRef();
  const canvasRef1 = useRef();

  const updateImageEvent = useEvent("UpdateImage", {
    bubbles: true,
    composed: true,
  });

  const addClick = (): void => {
    console.log("canva", canvasRef.current);
    html2canvas(canvasRef.current,
      {
        useCORS: true,
        allowTaint: true,
      }).then((canvas) => {
      canvasRef1.current.appendChild(canvas);
      canvas.toBlob(async (blob) => {
        const file = new File([blob], "filename.jpeg");
        const formdata = new FormData();
        formdata.append("file", file);
        const r = await requestUploadFile1(formdata);
        updateImageEvent(r);
      }, "image/jpeg", 0.95);
    });
  };

  return (
    <host shadowDom>
      <style>{style}</style>
      <button type="button" onclick={addClick}>Submit</button>
      <div ref={canvasRef1}>
        <slot name="content">
          {children}
        </slot>
      </div>
    </host>
  );
};

KunCanvasUpload.props = {
  message: {
    type: String,
    value: "kun-canvas-upload",
    reflect: true,
    event: {
      type: "changeMessage",
    },
  },
};

export default getComponentOrDefine("kun-canvas-upload", KunCanvasUpload);
