//    Copyright (C) 2016-2018 __COMPANY_NAME
//    All rights reserved
//
//    created by zone at 2018-05-12 21:16

const {ccclass, property, disallowMultiple, menu} = cc._decorator

export function pSetInLength(v: cc.Vec2, len: number) {
    v.normalizeSelf()
    v.mulSelf(len)
}


@ccclass
@disallowMultiple
@menu("View/SimpleBulletView")
export class SimpleBulletView extends cc.Component {
    id:number=0
    speed:cc.Vec2
    acc:number=0
    // endPos:cc.Vec2
    isDying=false
    _dyingCnt=0
    endPos:cc.Vec2

    inited=false

    isFirstUpdate=false
    start(){
    }
    reuse(id, pos:cc.Vec2,endPos,curVel:number, acc) {
        this.endPos=endPos
        this.isDying=false
        this._dyingCnt=0
        this.id = id;
        this.node.setPosition(pos);
        let dir=endPos.sub(pos)
        pSetInLength(dir,curVel)
        this.speed=dir
        this.acc = acc

        this.inited=true

        this.isFirstUpdate=true
    }
    unuse(){

    }
    lateUpdate(dt) {
        if(!this.inited)
            return

        if(this.isFirstUpdate){
            this.isFirstUpdate=false
            return
        }
        let speedLen;
        if(this.isDying)
            return
        speedLen = this.speed.mag()
        speedLen += this.acc * dt;
        pSetInLength(this.speed,speedLen)
        this.node.x += this.speed.x * dt;
        this.node.y += this.speed.y * dt;

        if(this.endPos) {
            let isXOver=false
            let isYOver=false
            if (this.speed.x > 0) {
                isXOver=this.node.x>=this.endPos.x
            }else{
                isXOver=this.node.x<=this.endPos.x
            }
            if (this.speed.y > 0) {
                isYOver=this.node.y>=this.endPos.y
            }else{
                isYOver=this.node.y<=this.endPos.y
            }
            if(isXOver&&isYOver){
                this.die(this.endPos)
                // this.destroy()
            }
        }
    }


    die(pos?:cc.Vec2) {
        if(this.isDying)
            return
        this.isDying=true
        if (pos) {
            this.node.setPosition(pos);
        }
        this.getComponent(cc.MotionStreak).reset()
        let disappearTime=0.2
        this.node.runAction(cc.sequence(
            cc.delayTime(disappearTime),
            cc.callFunc(()=>{
                this.node.destroy()
                this.inited=false
            })
        ));
    }
}