import { arrayToTree } from './array-to-tree';
/**
 * Manages data hierarchy within the table, including converting between a flat list of
 * data and hierarchical data.
 */
export class DataHierarchyManager {
    constructor(records, idFieldName, parentIdFieldName) {
        this.isDataFlat = false;
        if (typeof idFieldName === 'string'
            && typeof parentIdFieldName === 'string') {
            try {
                this._hierarchicalData = arrayToTree(records, {
                    id: idFieldName,
                    parentId: parentIdFieldName
                });
                this.isDataFlat = false;
                this._parentIdConfigurationValid = true;
            }
            catch {
                this.isDataFlat = true;
                this._hierarchicalData = records.map((record, index) => ({
                    clientRecord: record,
                    originalIndex: index
                }));
                this._parentIdConfigurationValid = false;
            }
        }
        else {
            this.isDataFlat = true;
            this._hierarchicalData = records.map((record, index) => ({
                clientRecord: record,
                originalIndex: index
            }));
            this._parentIdConfigurationValid = true;
        }
    }
    get hierarchicalData() {
        return this._hierarchicalData;
    }
    get parentIdConfigurationValid() {
        return this._parentIdConfigurationValid;
    }
    getAllRecords(sort = false) {
        const allNodes = [];
        this.getAllNodes(this._hierarchicalData, allNodes);
        if (this.isDataFlat || !sort) {
            // If the data is flat, then it was never reordered to support hierarchy.
            // Therefore, there is no need to sort the nodes.
            return allNodes.map(x => x.clientRecord);
        }
        return allNodes
            .sort((a, b) => a.originalIndex - b.originalIndex)
            .map(x => x.clientRecord);
    }
    getAllNodes(parentNodes, allNodes) {
        for (const parentNode of parentNodes) {
            allNodes.push(parentNode);
            if (parentNode.subRows) {
                this.getAllNodes(parentNode.subRows, allNodes);
            }
        }
    }
}
//# sourceMappingURL=data-hierarchy-manager.js.map