import { requireNotNull } from "@imengyu/imengyu-utils";
import { MiniRender } from "./MiniRender";

export class UniWeappRender implements MiniRender.RendeCanvasInterface {

  constructor(private id: string, private componentInstance: any) {
  }

  private ctx: CanvasRenderingContext2D | null = null;
  private width: number = 0;
  private height: number = 0;
  private canvas: any;

  async initCanvas(width: number, height: number): Promise<void> {
    this.width = width;
    this.height = height;
    await new Promise<void>((resolve) => {
      uni.createSelectorQuery()
        .in(this.componentInstance)
        .select('#' + this.id) // 在 WXML 中填入的 id
        .fields({ node: true }, (res) => {})
        .exec((res) => {
          const canvas = (res as any)[0].node
          canvas.width = width
          canvas.height = height
          this.canvas = canvas
          this.ctx = canvas.getContext('2d')
          resolve()
        });
    })
  }
  createImage(src: string) {
    return new Promise((resolve, reject) => {
      const image = this.canvas.createImage()
      image.onload = () => { resolve(image) }
      image.onerror = () => { reject(new Error('Failed to load image')) }
      image.src = src
    })
  }
  clearCanvas(): void {
    requireNotNull(this.ctx).clearRect(0, 0, this.width, this.height)
  }
  requestAnimationFrame(draw: (ts: number) => void): number {
    return this.canvas.requestAnimationFrame(draw)
  }
  cancelAnimationFrame(id: number): void {
    this.canvas.cancelAnimationFrame(id)
  }
  getCtx(): CanvasRenderingContext2D {
    return requireNotNull(this.ctx)
  }


}