"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Table = exports.TableRow = exports.TableCell = exports.StylableContainer = exports.TableColumnDefinition = void 0;
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
var card_elements_1 = require("./card-elements");
var enums_1 = require("./enums");
var registry_1 = require("./registry");
var serialization_1 = require("./serialization");
var shared_1 = require("./shared");
var strings_1 = require("./strings");
var utils_1 = require("./utils");
var TableColumnDefinition = /** @class */ (function (_super) {
    __extends(TableColumnDefinition, _super);
    function TableColumnDefinition() {
        //#region Schema
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.width = new shared_1.SizeAndUnit(1, enums_1.SizeUnit.Weight);
        return _this;
    }
    TableColumnDefinition.prototype.getSchemaKey = function () {
        return "ColumnDefinition";
    };
    TableColumnDefinition.horizontalCellContentAlignmentProperty = new serialization_1.EnumProperty(serialization_1.Versions.v1_5, "horizontalCellContentAlignment", enums_1.HorizontalAlignment);
    TableColumnDefinition.verticalCellContentAlignmentProperty = new serialization_1.EnumProperty(serialization_1.Versions.v1_5, "verticalCellContentAlignment", enums_1.VerticalAlignment);
    TableColumnDefinition.widthProperty = new serialization_1.CustomProperty(serialization_1.Versions.v1_5, "width", function (sender, prop, source, context) {
        var result = prop.defaultValue;
        var value = source[prop.name];
        var invalidWidth = false;
        if (typeof value === "number" && !isNaN(value)) {
            result = new shared_1.SizeAndUnit(value, enums_1.SizeUnit.Weight);
        }
        else if (typeof value === "string") {
            try {
                result = shared_1.SizeAndUnit.parse(value);
            }
            catch (e) {
                invalidWidth = true;
            }
        }
        else {
            invalidWidth = true;
        }
        if (invalidWidth) {
            context.logParseEvent(sender, enums_1.ValidationEvent.InvalidPropertyValue, strings_1.Strings.errors.invalidColumnWidth(value));
        }
        return result;
    }, function (sender, property, target, value, context) {
        if (value.unit === enums_1.SizeUnit.Pixel) {
            context.serializeValue(target, "width", value.physicalSize + "px");
        }
        else {
            context.serializeNumber(target, "width", value.physicalSize);
        }
    }, new shared_1.SizeAndUnit(1, enums_1.SizeUnit.Weight));
    __decorate([
        (0, serialization_1.property)(TableColumnDefinition.horizontalCellContentAlignmentProperty)
    ], TableColumnDefinition.prototype, "horizontalCellContentAlignment", void 0);
    __decorate([
        (0, serialization_1.property)(TableColumnDefinition.verticalCellContentAlignmentProperty)
    ], TableColumnDefinition.prototype, "verticalCellContentAlignment", void 0);
    __decorate([
        (0, serialization_1.property)(TableColumnDefinition.widthProperty)
    ], TableColumnDefinition.prototype, "width", void 0);
    return TableColumnDefinition;
}(serialization_1.SerializableObject));
exports.TableColumnDefinition = TableColumnDefinition;
var StylableContainer = /** @class */ (function (_super) {
    __extends(StylableContainer, _super);
    function StylableContainer() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._items = [];
        return _this;
    }
    StylableContainer.prototype.parseItem = function (source, context) {
        var _this = this;
        return context.parseCardObject(this, source, [], // Forbidden types not supported for elements for now
        !this.isDesignMode(), function (typeName) {
            return _this.createItemInstance(typeName);
        }, function (typeName, _errorType) {
            context.logParseEvent(undefined, enums_1.ValidationEvent.ElementTypeNotAllowed, strings_1.Strings.errors.elementTypeNotAllowed(typeName));
        });
    };
    StylableContainer.prototype.internalAddItem = function (item) {
        if (!item.parent) {
            this._items.push(item);
            item.setParent(this);
        }
        else {
            throw new Error(strings_1.Strings.errors.elementAlreadyParented());
        }
    };
    StylableContainer.prototype.internalRemoveItem = function (item) {
        var itemIndex = this._items.indexOf(item);
        if (itemIndex >= 0) {
            this._items.splice(itemIndex, 1);
            item.setParent(undefined);
            this.updateLayout();
            return true;
        }
        return false;
    };
    StylableContainer.prototype.internalIndexOf = function (item) {
        return this._items.indexOf(item);
    };
    StylableContainer.prototype.internalParse = function (source, context) {
        _super.prototype.internalParse.call(this, source, context);
        this._items = [];
        var items = source[this.getCollectionPropertyName()];
        if (Array.isArray(items)) {
            for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
                var item = items_1[_i];
                var instance = this.parseItem(item, context);
                if (instance) {
                    this._items.push(instance);
                }
            }
        }
    };
    StylableContainer.prototype.internalToJSON = function (target, context) {
        _super.prototype.internalToJSON.call(this, target, context);
        context.serializeArray(target, this.getCollectionPropertyName(), this._items);
    };
    StylableContainer.prototype.removeItem = function (item) {
        return this.internalRemoveItem(item);
    };
    StylableContainer.prototype.getItemCount = function () {
        return this._items.length;
    };
    StylableContainer.prototype.getItemAt = function (index) {
        return this._items[index];
    };
    StylableContainer.prototype.getFirstVisibleRenderedItem = function () {
        return this.getItemCount() > 0 ? this.getItemAt(0) : undefined;
    };
    StylableContainer.prototype.getLastVisibleRenderedItem = function () {
        return this.getItemCount() > 0 ? this.getItemAt(this.getItemCount() - 1) : undefined;
    };
    return StylableContainer;
}(card_elements_1.StylableCardElementContainer));
exports.StylableContainer = StylableContainer;
var TableCell = /** @class */ (function (_super) {
    __extends(TableCell, _super);
    function TableCell() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._columnIndex = -1;
        _this._cellType = "data";
        return _this;
    }
    TableCell.prototype.getHasBorder = function () {
        return this.parentRow.parentTable.showGridLines;
    };
    TableCell.prototype.applyBorder = function () {
        if (this.renderedElement && this.getHasBorder()) {
            var styleDefinition = this.hostConfig.containerStyles.getStyleByName(this.parentRow.parentTable.gridStyle);
            if (styleDefinition.borderColor) {
                var borderColor = (0, utils_1.stringToCssColor)(styleDefinition.borderColor);
                if (borderColor) {
                    this.renderedElement.style.borderRight = "1px solid " + borderColor;
                    this.renderedElement.style.borderBottom = "1px solid " + borderColor;
                }
            }
        }
    };
    TableCell.prototype.getDefaultPadding = function () {
        return this.getHasBackground() || this.getHasBorder()
            ? new shared_1.PaddingDefinition(enums_1.Spacing.Small, enums_1.Spacing.Small, enums_1.Spacing.Small, enums_1.Spacing.Small)
            : _super.prototype.getDefaultPadding.call(this);
    };
    TableCell.prototype.internalRender = function () {
        var cellElement = _super.prototype.internalRender.call(this);
        if (cellElement) {
            cellElement.setAttribute("role", this.cellType === "data" ? "cell" : "columnheader");
            cellElement.style.minWidth = "0";
            if (this.cellType === "header") {
                cellElement.setAttribute("scope", "col");
            }
        }
        return cellElement;
    };
    TableCell.prototype.shouldSerialize = function (_context) {
        return true;
    };
    TableCell.prototype.getJsonTypeName = function () {
        return "TableCell";
    };
    TableCell.prototype.getEffectiveTextStyleDefinition = function () {
        if (this.cellType === "header") {
            return this.hostConfig.textStyles.columnHeader;
        }
        return _super.prototype.getEffectiveTextStyleDefinition.call(this);
    };
    TableCell.prototype.getEffectiveHorizontalAlignment = function () {
        if (this.horizontalAlignment !== undefined) {
            return this.horizontalAlignment;
        }
        if (this.parentRow.horizontalCellContentAlignment !== undefined) {
            return this.parentRow.horizontalCellContentAlignment;
        }
        if (this.columnIndex >= 0) {
            var horizontalAlignment = this.parentRow.parentTable.getColumnAt(this.columnIndex).horizontalCellContentAlignment;
            if (horizontalAlignment !== undefined) {
                return horizontalAlignment;
            }
        }
        if (this.parentRow.parentTable.horizontalCellContentAlignment !== undefined) {
            return this.parentRow.parentTable.horizontalCellContentAlignment;
        }
        return _super.prototype.getEffectiveHorizontalAlignment.call(this);
    };
    TableCell.prototype.getEffectiveVerticalContentAlignment = function () {
        if (this.verticalContentAlignment !== undefined) {
            return this.verticalContentAlignment;
        }
        if (this.parentRow.verticalCellContentAlignment !== undefined) {
            return this.parentRow.verticalCellContentAlignment;
        }
        if (this.columnIndex >= 0) {
            var verticalAlignment = this.parentRow.parentTable.getColumnAt(this.columnIndex).verticalCellContentAlignment;
            if (verticalAlignment !== undefined) {
                return verticalAlignment;
            }
        }
        if (this.parentRow.parentTable.verticalCellContentAlignment !== undefined) {
            return this.parentRow.parentTable.verticalCellContentAlignment;
        }
        return _super.prototype.getEffectiveVerticalContentAlignment.call(this);
    };
    Object.defineProperty(TableCell.prototype, "columnIndex", {
        get: function () {
            return this._columnIndex;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TableCell.prototype, "cellType", {
        get: function () {
            return this._cellType;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TableCell.prototype, "parentRow", {
        get: function () {
            return this.parent;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TableCell.prototype, "isStandalone", {
        get: function () {
            return false;
        },
        enumerable: false,
        configurable: true
    });
    return TableCell;
}(card_elements_1.Container));
exports.TableCell = TableCell;
var TableRow = /** @class */ (function (_super) {
    __extends(TableRow, _super);
    function TableRow() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    //#endregion
    TableRow.prototype.getDefaultPadding = function () {
        return new shared_1.PaddingDefinition(enums_1.Spacing.None, enums_1.Spacing.None, enums_1.Spacing.None, enums_1.Spacing.None);
    };
    TableRow.prototype.applyBackground = function () {
        if (this.renderedElement) {
            var styleDefinition = this.hostConfig.containerStyles.getStyleByName(this.style, this.hostConfig.containerStyles.getStyleByName(this.defaultStyle));
            if (styleDefinition.backgroundColor) {
                var bgColor = (0, utils_1.stringToCssColor)(styleDefinition.backgroundColor);
                if (bgColor) {
                    this.renderedElement.style.backgroundColor = bgColor;
                }
            }
        }
    };
    TableRow.prototype.getCollectionPropertyName = function () {
        return "cells";
    };
    TableRow.prototype.createItemInstance = function (typeName) {
        return !typeName || typeName === "TableCell" ? new TableCell() : undefined;
    };
    TableRow.prototype.internalRender = function () {
        var isFirstRow = this.getIsFirstRow();
        var cellSpacing = this.hostConfig.table.cellSpacing;
        var rowElement = document.createElement("div");
        rowElement.setAttribute("role", "row");
        rowElement.style.display = "flex";
        rowElement.style.flexDirection = "row";
        for (var i = 0; i < Math.min(this.getItemCount(), this.parentTable.getColumnCount()); i++) {
            var cell = this.getItemAt(i);
            // Cheating a bit in order to keep cellType read-only
            cell["_columnIndex"] = i;
            cell["_cellType"] =
                this.parentTable.firstRowAsHeaders && isFirstRow ? "header" : "data";
            var renderedCell = cell.render();
            if (renderedCell) {
                var column = this.parentTable.getColumnAt(i);
                if (column.computedWidth.unit === enums_1.SizeUnit.Pixel) {
                    renderedCell.style.flex = "0 0 " + column.computedWidth.physicalSize + "px";
                }
                else {
                    renderedCell.style.flex = "1 1 " + column.computedWidth.physicalSize + "%";
                }
                if (i > 0 && !this.parentTable.showGridLines && cellSpacing > 0) {
                    renderedCell.style.marginLeft = cellSpacing + "px";
                }
                rowElement.appendChild(renderedCell);
            }
        }
        return rowElement.children.length > 0 ? rowElement : undefined;
    };
    TableRow.prototype.shouldSerialize = function (_context) {
        return true;
    };
    TableRow.prototype.addCell = function (cell) {
        this.internalAddItem(cell);
    };
    TableRow.prototype.removeCellAt = function (columnIndex) {
        if (columnIndex >= 0 && columnIndex < this.getItemCount()) {
            return this.removeItem(this.getItemAt(columnIndex));
        }
        return false;
    };
    TableRow.prototype.indexOf = function (cardElement) {
        return cardElement instanceof TableCell ? this.internalIndexOf(cardElement) : -1;
    };
    TableRow.prototype.ensureHasEnoughCells = function (cellCount) {
        while (this.getItemCount() < cellCount) {
            this.addCell(new TableCell());
        }
    };
    TableRow.prototype.getJsonTypeName = function () {
        return "TableRow";
    };
    TableRow.prototype.getIsFirstRow = function () {
        return this.parentTable.getItemAt(0) === this;
    };
    Object.defineProperty(TableRow.prototype, "parentTable", {
        get: function () {
            return this.parent;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TableRow.prototype, "isStandalone", {
        get: function () {
            return false;
        },
        enumerable: false,
        configurable: true
    });
    //#region Schema
    TableRow.styleProperty = new card_elements_1.ContainerStyleProperty(serialization_1.Versions.v1_5, "style");
    TableRow.horizontalCellContentAlignmentProperty = new serialization_1.EnumProperty(serialization_1.Versions.v1_5, "horizontalCellContentAlignment", enums_1.HorizontalAlignment);
    TableRow.verticalCellContentAlignmentProperty = new serialization_1.EnumProperty(serialization_1.Versions.v1_5, "verticalCellContentAlignment", enums_1.VerticalAlignment);
    __decorate([
        (0, serialization_1.property)(TableRow.horizontalCellContentAlignmentProperty)
    ], TableRow.prototype, "horizontalCellContentAlignment", void 0);
    __decorate([
        (0, serialization_1.property)(TableRow.verticalCellContentAlignmentProperty)
    ], TableRow.prototype, "verticalCellContentAlignment", void 0);
    return TableRow;
}(StylableContainer));
exports.TableRow = TableRow;
var Table = /** @class */ (function (_super) {
    __extends(Table, _super);
    function Table() {
        //#region Schema
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._columns = [];
        _this.firstRowAsHeaders = true;
        _this.showGridLines = true;
        return _this;
    }
    Object.defineProperty(Table.prototype, "gridStyle", {
        get: function () {
            var style = this.getValue(Table.gridStyleProperty);
            if (style && this.hostConfig.containerStyles.getStyleByName(style)) {
                return style;
            }
            return undefined;
        },
        set: function (value) {
            this.setValue(Table.gridStyleProperty, value);
        },
        enumerable: false,
        configurable: true
    });
    //#endregion
    Table.prototype.ensureRowsHaveEnoughCells = function () {
        for (var i = 0; i < this.getItemCount(); i++) {
            this.getItemAt(i).ensureHasEnoughCells(this.getColumnCount());
        }
    };
    Table.prototype.removeCellsFromColumn = function (columnIndex) {
        for (var i = 0; i < this.getItemCount(); i++) {
            this.getItemAt(i).removeCellAt(columnIndex);
        }
    };
    Table.prototype.getCollectionPropertyName = function () {
        return "rows";
    };
    Table.prototype.createItemInstance = function (typeName) {
        return !typeName || typeName === "TableRow" ? new TableRow() : undefined;
    };
    Table.prototype.internalParse = function (source, context) {
        _super.prototype.internalParse.call(this, source, context);
        this.ensureRowsHaveEnoughCells();
    };
    Table.prototype.internalRender = function () {
        if (this.getItemCount() > 0) {
            var totalWeights = 0;
            for (var _i = 0, _a = this._columns; _i < _a.length; _i++) {
                var column = _a[_i];
                if (column.width.unit === enums_1.SizeUnit.Weight) {
                    totalWeights += column.width.physicalSize;
                }
            }
            for (var _b = 0, _c = this._columns; _b < _c.length; _b++) {
                var column = _c[_b];
                if (column.width.unit === enums_1.SizeUnit.Pixel) {
                    column.computedWidth = new shared_1.SizeAndUnit(column.width.physicalSize, enums_1.SizeUnit.Pixel);
                }
                else {
                    column.computedWidth = new shared_1.SizeAndUnit((100 / totalWeights) * column.width.physicalSize, enums_1.SizeUnit.Weight);
                }
            }
            var tableElement = document.createElement("div");
            tableElement.setAttribute("role", "table");
            tableElement.style.display = "flex";
            tableElement.style.flexDirection = "column";
            if (this.showGridLines) {
                var styleDefinition = this.hostConfig.containerStyles.getStyleByName(this.gridStyle);
                if (styleDefinition.borderColor) {
                    var borderColor = (0, utils_1.stringToCssColor)(styleDefinition.borderColor);
                    if (borderColor) {
                        tableElement.style.borderTop = "1px solid " + borderColor;
                        tableElement.style.borderLeft = "1px solid " + borderColor;
                    }
                }
            }
            var cellSpacing = this.hostConfig.table.cellSpacing;
            for (var i = 0; i < this.getItemCount(); i++) {
                var renderedRow = this.getItemAt(i).render();
                if (renderedRow) {
                    if (i > 0 && !this.showGridLines && cellSpacing > 0) {
                        var separatorRow = document.createElement("div");
                        separatorRow.setAttribute("aria-hidden", "true");
                        separatorRow.style.height = cellSpacing + "px";
                        tableElement.appendChild(separatorRow);
                    }
                    tableElement.appendChild(renderedRow);
                }
            }
            return tableElement;
        }
        return undefined;
    };
    Table.prototype.addColumn = function (column) {
        this._columns.push(column);
        this.ensureRowsHaveEnoughCells();
    };
    Table.prototype.removeColumn = function (column) {
        var index = this._columns.indexOf(column);
        if (index >= 0) {
            this.removeCellsFromColumn(index);
            this._columns.splice(index, 1);
        }
    };
    Table.prototype.getColumnCount = function () {
        return this._columns.length;
    };
    Table.prototype.getColumnAt = function (index) {
        return this._columns[index];
    };
    Table.prototype.addRow = function (row) {
        this.internalAddItem(row);
        row.ensureHasEnoughCells(this.getColumnCount());
    };
    Table.prototype.indexOf = function (cardElement) {
        return cardElement instanceof TableRow ? this.internalIndexOf(cardElement) : -1;
    };
    Table.prototype.getJsonTypeName = function () {
        return "Table";
    };
    Table._columnsProperty = new serialization_1.SerializableObjectCollectionProperty(serialization_1.Versions.v1_5, "columns", TableColumnDefinition);
    Table.firstRowAsHeadersProperty = new serialization_1.BoolProperty(serialization_1.Versions.v1_5, "firstRowAsHeaders", true);
    Table.showGridLinesProperty = new serialization_1.BoolProperty(serialization_1.Versions.v1_5, "showGridLines", true);
    Table.gridStyleProperty = new card_elements_1.ContainerStyleProperty(serialization_1.Versions.v1_5, "gridStyle");
    Table.horizontalCellContentAlignmentProperty = new serialization_1.EnumProperty(serialization_1.Versions.v1_5, "horizontalCellContentAlignment", enums_1.HorizontalAlignment);
    Table.verticalCellContentAlignmentProperty = new serialization_1.EnumProperty(serialization_1.Versions.v1_5, "verticalCellContentAlignment", enums_1.VerticalAlignment);
    __decorate([
        (0, serialization_1.property)(Table._columnsProperty)
    ], Table.prototype, "_columns", void 0);
    __decorate([
        (0, serialization_1.property)(Table.firstRowAsHeadersProperty)
    ], Table.prototype, "firstRowAsHeaders", void 0);
    __decorate([
        (0, serialization_1.property)(Table.showGridLinesProperty)
    ], Table.prototype, "showGridLines", void 0);
    __decorate([
        (0, serialization_1.property)(Table.gridStyleProperty)
    ], Table.prototype, "gridStyle", null);
    __decorate([
        (0, serialization_1.property)(Table.horizontalCellContentAlignmentProperty)
    ], Table.prototype, "horizontalCellContentAlignment", void 0);
    __decorate([
        (0, serialization_1.property)(Table.verticalCellContentAlignmentProperty)
    ], Table.prototype, "verticalCellContentAlignment", void 0);
    return Table;
}(StylableContainer));
exports.Table = Table;
registry_1.GlobalRegistry.defaultElements.register("Table", Table, serialization_1.Versions.v1_5);
//# sourceMappingURL=table.js.map