import { BitmapNumber } from "../class/BitmapNumber";
import { Tool } from "../Tool";
import { Pool } from "../Pool";
import { RecoverName } from "../enum/RecoverName";

/**
 * 位图数字 目标元素数量
 * 不管多少位,都按中间数字居中
 * 暂不做通用,以后再说,否则回收问题
 */
export class CurScoreNum extends egret.DisplayObjectContainer {
    /**
     * 数字
     */
    private _num: number;
    get num(): number {
        return this._num
    }
    set num(value: number) {
        if (value == this._num) return;
        this._num = value;
        var arr = Tool.returnTO(value);
        //位数从小到大add,
        for (var i = 0; i < arr.length; i++) {
            if (this.$children[i]) {
                //先用完原先$children里的,不通用就没必要修改resName
                this.$children[i]["num"] = arr[i];
            } else {
                //如果没有就
                let o: BitmapNumber = Pool.takeOut(RecoverName.BITMAP_NUMBER);
                if (!o) {
                    o = new BitmapNumber("curScoreNum");
                } else {
                    o.reset("curScoreNum")
                }
                o.num = arr[i];
                this.addChild(o)
            }
        }
        //如果多了,去掉后面的,回收
        if (this.$children.length > arr.length) {
            //移除后序
            for (var i = this.$children.length - 1; i >= arr.length; i--) {
                let c = this.$children[i];
                this.removeChild(c);
                Pool.recover(RecoverName.BITMAP_NUMBER, c);
            }
        }
        //居中适配
        this.center()
    }

    constructor() {
        super();
        this.num = 0;
    }

    /**
     * 居中位置
     */
    center() {
        //按顺序排,从右到左,
        var len = this.$children.length;
        var w = this.$children[0]["texture"].textureWidth - 4;
        var right = len / 2 * w - w + len / 2 * w;
        for (var i = 0; i < this.$children.length; i++) {
            this.$children[i].x = right - w * i;
        }
    }
}