import Global from "./Global";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Brick extends cc.Component {
    private static counterId = 1;

    private manager = null;
    private isObstacle = false;
    private id = 0;
    private collider: cc.PhysicsBoxCollider = null;
    onLoad() {
        this.collider = this.node.getComponent(cc.PhysicsBoxCollider);
    }

    public get ID() {
        return this.id;
    }

    reuse(manager) {
        this.manager = manager;
        this.id = Brick.counterId++;
    }

    init(isObstacle: boolean, color: cc.Color, width: number, physicWidth: number) {
        this.isObstacle = isObstacle;
        this.node.color = color;
        this.node.width = width;
        this.node.height = width;

        if (isObstacle) {
            this.collider.tag = Global.TAG_Obstacle;
        } else {
            this.collider.tag = 0;
        }

        this.collider.size = cc.size(physicWidth, physicWidth);
        this.collider.apply();
    }

    recycle() {
        this.manager.recycleBrick(this);
    }

    // 只在两个碰撞体开始接触时被调用一次
    onBeginContact(contact: cc.PhysicsContact, selfCollider: cc.Collider, otherCollider: cc.Collider) {
        if (this.isObstacle) {
            return;
        }
        this.node.runAction(cc.callFunc(this.recycle, this));
    }
}
