import { Canvg, presets } from 'canvg'
import { toPng } from 'html-to-image'
import { addWatermark } from '/src/subpages/colexiu-share/wr'

// https://gist.githubusercontent.com/n1ru4l/9c7eff52fe084d67ff15ae6b0af5f171/raw/da9fe36d72171d4e36b92aced587b48dc5182792/offscreen-canvas-polyfill.js
if (!window.OffscreenCanvas) {
  // @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

      // @ts-ignore
      this.canvas.convertToBlob = () => {
        return new Promise((resolve) => {
          this.canvas.toBlob(resolve)
        })
      }

      // @ts-ignore
      return this.canvas
    }
  }
}

const preset = presets.offscreen()

function blobToBase64(blob: Blob) {
  return new Promise((resolve, _) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.readAsDataURL(blob)
  })
}

export async function svgtopng(svg: string, width: number, height: number) {
  const canvas = new OffscreenCanvas(width, height)
  const ctx = canvas.getContext('2d')!
  const v = 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)
  // console.log(base64)
  return base64
}

function loadImg(img: string) {
  return new Promise<HTMLImageElement>((resolve, reject) => {
    const pic = new Image()
    pic.onload = () => resolve(pic)
    pic.onerror = () => reject(new Error('Could not load image: ' + img))
    pic.src = img
  })
}

/**
 * 由于渲染时无需图片，标题需要后面再加
 * @param tit 标题信息
 * @param img 曲谱内容
 */
export async function additionalTitle(tit: string, img: string) {
  const bimg = await loadImg(img)
  const div = document.createElement('div')
  div.textContent = tit
  div.style.width = (bimg.width / 2) + 'px'
  div.style.fontSize = '36px'
  div.style.textAlign = 'center'
  div.style.padding = '10px 20px'
  div.style.paddingTop = '20px'
  div.style.backgroundColor = '#fff'
  document.body.appendChild(div)
  const t = await toPng(div)
  div.remove()
  const timg = await loadImg(t)
  const canvas = new OffscreenCanvas(bimg.width, timg.height + bimg.height)
  const ctx = canvas.getContext('2d')
  ctx?.drawImage(timg, 0, 0, timg.width, timg.height)
  ctx?.drawImage(bimg, 0, timg.height, bimg.width, bimg.height)
  addWatermark(canvas as any)
  const blob = await canvas.convertToBlob()
  // console.log(t, div, timg.width, timg.height, bimg.width, bimg.height)
  return await blobToBase64(blob)
}
