import { getTextureByName } from "./utils";
import { BaseSprite } from "./BaseSprite";

export class EffectAnim extends BaseSprite{
    bodyImg:engine.Image;
    titleName:string = '';
    count:number = 2;
    textureArr:engine.Texture[] = [];
    effectFrame:number = 0;
    maxCount:number = 0;
    intervalHandler;
    callBack:Function;
    arg:any;
    loop:boolean = false;
    repeatCount:number = 0;
    maxRepeatCount:number = 0;
    constructor(titleName:string,effectFrame:number,maxCount:number,x:number,y:number,callBack:Function,arg:any,loop=false,maxRepeatCount:number = 0){
        super();
        this.titleName = titleName;
        this.effectFrame = effectFrame;
        this.maxCount = maxCount;
        this.x = x;
        this.y = y;
        this.callBack = callBack;
        this.arg = arg;
        this.loop = loop;
        this.maxRepeatCount = maxRepeatCount;
    }

    addToViewPort(){
        super.addToViewPort();
        this.bodyImg = new engine.Image(getTextureByName(this.titleName+1));
        this.bodyImg.x = -this.bodyImg.width>>1;
        this.bodyImg.y = -this.bodyImg.height>>1;
        this.addChild(this.bodyImg);
        this.setTextureArr();
        this.playEffect();
    }

    /**设置纹理组 */
    setTextureArr(){
        for(var i=1;i<=this.maxCount;i++){
            var texture = getTextureByName(this.titleName+i);
            this.textureArr.push(texture);
        }
        // if(this.titleName == "polymerization"){
        //     console.log(this.textureArr);
        // }
    }

    /**播放特效 */
    playEffect(){
        var that = this;
        that.intervalHandler = setInterval(()=>{
            that.bodyImg.texture = that.textureArr[that.count-1];
            that.bodyImg.x = -that.bodyImg.width>>1;
            that.bodyImg.y = -that.bodyImg.height>>1;
            that.count++;
            if(this.loop&&that.count>that.maxCount){
                // if(that.callBack&&that.arg){
                //     that.callBack.call(that.arg);
                // }
                that.repeatCount ++;
                if(that.maxRepeatCount>0&&that.repeatCount>=that.maxRepeatCount){
                    that.loop = false;
                    that.removeEffect();
                }
                that.count = 1;
            }else if(that.count>that.maxCount){
                that.removeEffect();
            }
        },that.effectFrame)
    }

    removeEffect(){
        var that = this;
        clearInterval(that.intervalHandler);
        if(that.callBack&&that.arg){
            that.callBack.call(that.arg);
        }
        that.callBack = that.arg = null;
        if(that&&that.parent){
            that.parent.removeChild(that);
        }
    }

    removeFromViewPort(){
        super.removeFromViewPort();
        var that = this;
        clearInterval(that.intervalHandler);
        if(that.callBack&&that.arg){
            that.callBack.call(that.arg);
        }
        that.callBack = that.arg = null;
    }
}