
import { _decorator, Component, Node, Collider2D, Contact2DType, IPhysics2DContact, RigidBody2D } from 'cc';
import { PhysicsGroup } from './Constants';
import { Enemy } from './Enemy';
import { ObjPool } from './ObjPool';
const { ccclass, property } = _decorator;


@ccclass('Bullet')
export class Bullet extends Component {
    @property
    damage: number = 10;

    lifeTime: number = 0;
    isDie: boolean = false;

    rb2d: RigidBody2D;

    onLoad() {
        this.rb2d = this.getComponent(RigidBody2D);
        this.getComponent(Collider2D).on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }

    onEnable() {
        this.isDie = false;
        this.rb2d.wakeUp();
        this.lifeTime = 3;
    }

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact) {
        if(otherCollider.group & PhysicsGroup.Enemy) {
            this.die();
            otherCollider.node.getComponent(Enemy).takeDamage(this.damage);
        }
    }

    die() {
        this.rb2d.sleep();
        this.lifeTime = 0;
        this.isDie = true;
        this.scheduleOnce(() => {
            ObjPool.putNode(this.node);
        });
    }

    update(dt: number) {
        if(this.isDie) {
            return;
        }
        this.lifeTime -= dt;
        if(this.lifeTime <= 0) {
            this.die();
        }
    }
}