import { I as ImageElement } from "./image-element.js";
import { g as getFrames } from "./gif-utils.js";
import "./defaults.js";
import "./index.js";
import "vue";
import "./watermark.js";
import "./v4.js";
import "./gif-apng.worker.js";
function createAnimationImageElement(editor) {
  return class AnimationImageElement extends ImageElement {
    constructor(options, engine) {
      super(options, engine);
      this.clockInElement = -1;
      this.url = "";
      this.loop = options.loop;
      this.$editorElement = this.options.$element || editor.getElement(this.id);
      this.resetClipByElement();
    }
    async init() {
      await super.init();
      await this.loadFrames();
      await this.initFrameBuffer();
    }
    async initFrameBuffer() {
      if (this.$layer.source) {
        if (this.$frameBuffer) {
          await this.$frameBuffer.destory();
        }
        const canvas = this.$frames[0].canvas;
        this.$frameBuffer = await this.$engine.createFrameBuffer(canvas.width, canvas.height);
        await this.$frameBuffer.setTexture(canvas);
        await this.$layer.source.setFrameBuffer(this.$frameBuffer);
      }
    }
    resetClipByElement() {
      this.width = this.$editorElement.width;
      this.height = this.$editorElement.height;
      this.naturalWidth = this.$editorElement.width;
      this.naturalHeight = this.$editorElement.height;
      this.scaleX = 1;
      this.scaleY = 1;
      this.innerLeft = 0;
      this.innerTop = 0;
    }
    loadFrames() {
      return getFrames(this.$editorElement).then((frames) => {
        let totalDuration = 0;
        frames.forEach((frame) => {
          const duration = frame.delay;
          frame.duration = duration;
          frame.delay = totalDuration;
          totalDuration += duration;
        });
        return {
          frames,
          duration: totalDuration
        };
      }).then(({ frames, duration }) => {
        this.selfDuration = duration;
        this.$frames = frames;
      });
    }
    findFrameByClock() {
      if (!this.loop && this.clockInElement > this.selfDuration) {
        return this.$frames[this.$frames.length - 1];
      } else {
        const frame = this.$frames.find((f) => {
          const { delay, duration } = f;
          const clock = this.clockInElement;
          return clock >= delay && clock <= delay + duration;
        });
        return frame;
      }
    }
    renderImage(clockInTimeline) {
      const clockInElement = this.calculateClock(clockInTimeline);
      if (this.clockInElement !== clockInElement) {
        this.clockInElement = clockInElement;
        const frame = this.findFrameByClock();
        return this.$frameBuffer.setTexture(frame.canvas);
      }
      return Promise.resolve();
    }
  };
}
export { createAnimationImageElement as default };
