import { Canvg, presets } from 'canvg'

// https://gist.githubusercontent.com/n1ru4l/9c7eff52fe084d67ff15ae6b0af5f171/raw/da9fe36d72171d4e36b92aced587b48dc5182792/offscreen-canvas-polyfill.js
if (!window.OffscreenCanvas) {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  window.OffscreenCanvas = class OffscreenCanvas {
    canvas: HTMLCanvasElement
    constructor(width: number, height: number) {
      this.canvas = document.createElement('canvas')
      this.canvas.width = width
      this.canvas.height = height

      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      this.canvas.convertToBlob = () => {
        return new Promise(resolve => {
          this.canvas.toBlob(resolve)
        })
      }

      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      return this.canvas
    }
  }
}

const preset = presets.offscreen()
const blobToBase64 = (blob: any) => {
  return new Promise((resolve, _) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.readAsDataURL(blob)
  })
}
let canvas = null as any
export const svgtopng = async (svg: any, width: any, height: any) => {
  console.log(canvas, +new Date() + '-----')

  if (!canvas) {
    canvas = new OffscreenCanvas(width, height)
  }

  const ctx = canvas.getContext('2d')!
  let v: any = await Canvg.fromString(ctx!, svg, preset)

  /**
   * Resize SVG to fit in given size.
   * @param width
   * @param height
   * @param preserveAspectRatio
   */
  v.resize(width * 2, height * 2, 'xMidYMid meet')

  // Render only first frame, ignoring animations and mouse.
  await v.start()
  const blob = await canvas.convertToBlob()
  const base64 = await blobToBase64(blob)
  // canvas.drawImage(base64
  // await v.stop()
  // releaseCanvas(canvas)
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  // canvas = null
  console.log(canvas, 'draw')
  await v.stop()
  v = null
  return base64
}

// function releaseCanvas(canvasElement) {
//   // 清空 Canvas 上的内容
//   const ctx = canvasElement.getContext('2d')
//   ctx.clearRect(0, 0, canvasElement.width, canvasElement.height)

//   // 停止任何正在进行的动画或定时器
//   cancelAnimationFrame(canvasElement.animationId)
//   // 删除对 Canvas 元素的引用
//   canvasElement = null
// }
