import { isMobile } from "./isMoblie";
import gsap from "gsap";
import mitt from "mitt";
class Mitt {
  constructor(e) {
    Object.assign(this, mitt(e));
  }
}
export class CanvasPlayer extends Mitt {
  constructor(canvasId, setting) {
    super();
    this.canvas = null;
    this.canvasId = canvasId;
    this.context = null;
    this.vw = null;
    this.vh = null;
    this.imageW = null;
    this.imageH = null;
    this.setting = setting;
    this.currentFrame = 0;
    this.currentType = 0;
    this.frames = [];
    this.clips = [
      {
        id: "clip-3",
        total: 298,
        x: 0,
        animation: null,
      },
    ];
    this.canScroll = false;
    this.resize = this.resize.bind(this);
    this.watchScroll = this.watchScroll.bind(this);
  }
  init() {
    this.canvas = document.getElementById(this.canvasId);
    this.context = this.canvas.getContext("2d", {
      alpha: true,
      desynchronized: true,
      powerPreference: "high-performance",
    });
    this.vw = this.canvas.width = window.innerWidth;
    this.vh = this.canvas.height = window.innerHeight;
    this.imageW = isMobile() ? 750 : 1920;
    this.imageH = isMobile() ? 1334 : 1080;
    this.proload();
    this.loadEvent();
  }

  loadImage(url) {
    return new Promise((resolve, reject) => {
      const img = new Image(this.imageW, this.imageH);
      img.onload = () => {
        resolve(img);
      };
      img.onerror = (error) => {
        resolve();
      };
      img.src = url;
    });
  }

  proload() {
    if (this.setting) {
      const list = [];
      Array.from(this.setting).forEach((item) => {
        console.log("item", item);
        for (let key = 0; key < item.total; key++) {
          const padLength = item.total.toString().length + 1;
          let imgIndex = String(key).padStart(padLength, "0");
          let url = `${item.imageUrl}/${imgIndex}.webp`;
          const res = this.loadImage(url).then((image) => {
            if (image) {
              const frame = {
                id: item.sectionType,
                index: key,
                image: image,
                total: item.total,
              };
              this.context.drawImage(image, 0, 0, this.vw, this.vh);
              this.frames.push(frame);
            }
          });
          list.push(res);
        }
      });
      Promise.all(list).then(() => {
        console.warn("all load");
        this.emit("loaded");
      });
    }
  }
  loadEvent() {
    window.addEventListener("resize", this.resize, false);
    window.addEventListener("wheel", this.watchScroll, false);
  }
  unLoadEvent() {
    window.removeEventListener("resize", this.resize, false);
    window.removeEventListener("wheel", this.watchScroll, false);
  }
  resize() {
    this.vw = this.canvas.width = window.innerWidth;
    this.vh = this.canvas.height = window.innerHeight;
  }
  enableScroll(type = 0) {
    this.canScroll = true;
    this.currentType = type;
  }
  unEnableScroll() {
    this.canScroll = false;
  }

  watchScroll(event) {
    if (this.canScroll) {
      // console.log("TweenLite", TweenLite);
      if (event.deltaY > 0) {
        this.currentFrame < 1 ? (this.currentFrame = 1) : this.currentFrame++;
      } else {
        this.currentFrame < 1 ? (this.currentFrame = 1) : this.currentFrame--;
      }
      this.reDraw(this.currentFrame, this.currentType);
    }
  }
  autoIncrement(na) {
    if (this.currentFrame > 0) {
      if (na) {
        this.currentFrame++;
        this.reDraw(this.currentFrame, this.currentType);
      } else {
        this.currentFrame--;
        this.reDraw(this.currentFrame, this.currentType);
      }
    }
  }

  play() {
    // this.currentType = type;
    // this.reDraw(frame, type);
  }
  initClipAnimate() {
    Array.from(this.clips).forEach((item) => {
      const time = "";

      // const anmi = gsap.to(this.clips[0], 1, {
      //   x: this.clips[0].total - 1,
      //   repeat: 0,
      //   duration: (this.clips[0].total / 2) * 1000,
      //   ease: "none",
      //   yoyo: true,
      //   onComplete: () => {
      //     console.log("done");
      //   },
      //   onUpdate: () => {
      //     const frame = Math.floor(this.clips[0].x);
      //     console.log("x", frame);
      //     this.reDraw(frame, this.currentType);
      //   },
      // });
    });
  }
  autoPlay() {
    console.log("this.clips[0]", (this.clips[0].total / 2) * 1000);
  }

  reDraw(frame, type) {
    if (isMobile()) {
    } else {
      this.context.clearRect(0, 0, this.vw, this.vh);
      const frames = this.frames.find(
        (item) => item.id == type && item.index == frame
      );
      if (frames && frames.index <= frames.total) {
        frames && this.context.drawImage(frames.image, 0, 0, this.vw, this.vh);
      }
    }
  }

  update() {}
}
