import { addImage } from "./utils";
import { FACTOR } from "./consts";

/**
 * 被打的砖块
 */
export default class Brick extends p2.Body {
    _skin: egret.DisplayObjectContainer;
    _initNums: number;
    _numText: egret.TextField;
    constructor(initNums) {
        super();
        this._initNums = initNums;
        this.type = p2.Body.KINEMATIC;
        this.init();
    }

    updateText() {
        this._numText.text = this._initNums + '';
        this._numText.y = this._skin.height / 2 - this._numText.textHeight / 2;
    }

    collideWithBall() {
        if (this._initNums > 0)
            this._initNums--;
        if (this._initNums <= 0) {
            this._skin.dispatchEvent(new egret.Event('destroy', false, false, this));
        }
        this.updateText();
    }

    onceDestroy(listener: Function, thisobj: any) {
        this._skin.once('destroy', listener, thisobj);
    }

    init() {
        this._skin = new egret.Sprite();
        this._numText = new egret.TextField();
        this._numText.textColor = 0xffffff;
        this._numText.size = 40;
        const bg = addImage('rect1_png');
        this._skin.addChild(bg);
        this._skin.addChild(this._numText);
        this._numText.width = bg.width;
        this._numText.textAlign = egret.HorizontalAlign.CENTER;

        this._skin.anchorOffsetX = this._skin.width / 2;
        this._skin.anchorOffsetY = this._skin.height / 2;

        const width = this._skin.width / FACTOR;
        const height = this._skin.height / FACTOR;
        const shape = new p2.Box({ width: width, height: height });
        this.addShape(shape);

        shape.collisionMask = 6;//010与001为0，010与110为1

        this.updateText();
    }

    updateSkin() {
        this._skin.x = this.position[0] * FACTOR;
        this._skin.y = this.position[1] * FACTOR;
        this._skin.rotation = this.angle * 180 / Math.PI;
    }

    get skin() { return this._skin }
}