import SVGAMgr from "../Mgr/SVGAMgr";
import { PoolElement } from "./Pool";

export default class MSVGAClip implements PoolElement {
    public svga: SVGAMovieClip = null;
    public onComplete: () => void;
    public onFrame: (frame: number) => void;
    public name: string = "";

    private loop: boolean = true;
    private destroyOnComplete: boolean = true;
    private bugFix = false;

    constructor(name: string, svga: SVGAMovieClip) {
        this.name = name;
        this.svga = svga;
    }

    public play(pos: number = 1, loop: boolean = true, destroyOnComplete: boolean = true) {
        this.loop = loop;
        this.destroyOnComplete = destroyOnComplete;

        this.svga.addEventListener(egret.Event.ENTER_FRAME, this.onSVGAFrame, this);
        this.svga.addEventListener(egret.Event.COMPLETE, this.onSVGAComplete, this);

        this.svga.gotoAndPlay(pos, true);
        if (this.bugFix) {
            this.svga.visible = true;
        }
    }

    public destroy() {
        this.stop(); //停止以删除监听器
        this.svga.destroy();
    }

    public stop(pos?: number) {
        this.svga.gotoAndStop(pos || this.svga.currentFrame);
        this.svga.removeEventListener(egret.Event.COMPLETE, this.onSVGAComplete, this);
        this.svga.removeEventListener(egret.Event.ENTER_FRAME, this.onSVGAFrame, this);
    }

    public setPosition(x: number = 0, y: number = 0, offsetX = 0, offsetY = 0) {
        this.svga.x = x + offsetX;
        this.svga.y = y + offsetY;
    }


    private onSVGAFrame() {
        if (!this.bugFix && this.svga.currentFrame >= 2) {
            this.svga.visible = true;
            this.bugFix = true;
        }
        this.onFrame && this.onFrame(this.svga.currentFrame);
    }

    private onSVGAComplete() {
        this.onComplete && this.onComplete();
        if (!this.loop && this.destroyOnComplete) {
            this.destroy();
        } else {
            if (!this.loop) {
                this.stop();
            }
        }
    }

    onElementRecycle() {
        this.stop();
        this.svga.visible = false;
        this.onComplete = null;
        this.onFrame = null;
        this.stop(1);
    }
    onElementInit() {

    }
}