export default class LineLayoutGroup extends eui.Group {
    public type: LineLayoutGroupType = LineLayoutGroupType.Vertical;

    /**在网格布局时水平方向上排序数量的限制 */
    public horizontalCountLimit = 1;

    constructor(type: LineLayoutGroupType = LineLayoutGroupType.Vertical, horizontalCountLimit?: number) {
        super();
        this.type = type;
        this.horizontalCountLimit = horizontalCountLimit;
        this.addEventListener(egret.Event.RESIZE, () => {
            this.order();
        }, this);
    }

    private order() {
        switch (this.type) {
            case LineLayoutGroupType.Vertical:
                this.orderVertical();
                break;
            case LineLayoutGroupType.Horizontal:
                this.orderHorizontal();
                break;

            case LineLayoutGroupType.Grid:
                this.orderGrid();
                break;
        }
    }

    private orderVertical() {
        let layoutHeight = 0;
        this.$children.forEach(child => {
            child.y = layoutHeight;
            layoutHeight += child.height;
        });
    }

    private orderHorizontal() {
        let layoutWidth = 0;
        this.$children.forEach(child => {
            child.x = layoutWidth;
            layoutWidth += child.width;
        });
    }

    private orderGrid() {
        let horLimitCount = 0;
        let curY = 0;
        let curX = 0;
        let maxChildHeight = 0;

        this.$children.forEach(child => {
            if (horLimitCount >= this.horizontalCountLimit) { //另起一行
                curY += maxChildHeight;
                maxChildHeight = 0;
                curX = 0;
                horLimitCount = 0;
            }

            child.x = curX;
            child.y = curY;

            curX += child.width;
            if (child.height > maxChildHeight) {
                maxChildHeight = child.height;
            }
            horLimitCount++;
        });
    }
}

export enum LineLayoutGroupType {
    Vertical,
    Horizontal,
    Grid
}