import { _decorator, Component, Node, AnimationComponent } from 'cc';
import CCSAnimationUtils from '../../../../engines/utils/CCSAnimationUtils';
const { ccclass, property } = _decorator;

@ccclass('FenceBase')
export class FenceBase extends Component {

    hp:number;

    maxHp:number;

    private animation:AnimationComponent;
    /**
     * 状态 0 站立 1 受伤 2 死亡
     */
    private state:number=0;

    start () {
        // Your initialization goes here.
        this.animation=this.getComponent(AnimationComponent);
        CCSAnimationUtils.SetAnimationSpeed(this.animation,this.config.idleAnimation,this.config.idleAnimationSpeed);
        CCSAnimationUtils.SetAnimationSpeed(this.animation,this.config.damageAnimation,this.config.damageAnimationSpeed);
        CCSAnimationUtils.SetAnimationSpeed(this.animation,this.config.dieAnimation,this.config.dieAnimationSpeed);
    }

    set config(value:any){
        this.__config=value;
        this.hp=this.maxHp=this.config.hp;
    }
    
    private __config:any;
    get config():any{
        return this.__config;
    }

    /**
     * 闲置
     */
    Stance():void{
        if(this.state==0){
            return;
        }
        this.state=0;
        this.animation.play(this.config.idleAnimation);
    }

    /**
     * 受伤
     * @param value 
     */
    Damage(value:number):void{
        if(this.IsDie){
            throw new Error("栅栏已经死了但是还受到了攻击！");
        }
        this.hp-=value;
        if(this.hp<=0){
            this.hp=0;
            this.Die();
        }else{
            this.state=1;
            this.removeAllAnimationCallBack();
            this.animation.on(AnimationComponent.EventType.FINISHED,this.DamageComplete,this,true);
            this.animation.play(this.config.damageAnimation);
        }
    }

    private DamageComplete():void{
        if(this.state==2){
            return;
        }
        this.Stance();
    }

    /**
     * 死亡
     */
    Die():void{
        if(this.state==2){
            return;
        }
        this.state=2;
        this.removeAllAnimationCallBack();
        this.animation.on(AnimationComponent.EventType.FINISHED,this.DieComplete,this,true);
        this.animation.play(this.config.dieAnimation);
    }

    private DieComplete():void{
        this.node.destroy();
    }

    get IsDie():boolean{
        if(this.hp<=0){
            return true;
        }
        return false;
    }

    private removeAllAnimationCallBack():void{
        if(this.animation.hasEventListener(AnimationComponent.EventType.FINISHED,this.DamageComplete,this)){
            this.animation.off(AnimationComponent.EventType.FINISHED,this.DamageComplete,this);
        }
    }
    
    // update (deltaTime: number) {

    // }
}
