"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AggregationsSection = exports.AggregationsSectionSummary = exports.isAggregationsSectionValid = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const CheckBox_1 = require("../../../../components/CheckBox");
const DropdownButton_1 = tslib_1.__importDefault(require("../../../../components/DropdownButton"));
const FormLayout_1 = tslib_1.__importStar(require("../../../../components/FormLayout"));
const Tabs_1 = require("../../../../components/Tabs");
const Tag_1 = require("../../../../components/Tag");
const AdaptableContext_1 = require("../../../AdaptableContext");
const ValueSelector_1 = require("../../../Components/ValueSelector");
const OnePageAdaptableWizard_1 = require("../../../Wizard/OnePageAdaptableWizard");
const Utilities_1 = require("./Utilities");
const ArrayExtensions_1 = tslib_1.__importDefault(require("../../../../Utilities/Extensions/ArrayExtensions"));
const Select_1 = require("../../../../components/Select");
const StringExtensions_1 = tslib_1.__importDefault(require("../../../../Utilities/Extensions/StringExtensions"));
const Flex_1 = require("../../../../components/Flex");
const WEIGHTED_AVERAGE_AGG_FN_NAME = 'weightedAvg';
const isAggregationsSectionValid = (data) => {
    const weightedAvg = data.TableAggregationColumns
        ? (data.TableAggregationColumns || []).find(({ AggFunc }) => typeof AggFunc === 'object' &&
            AggFunc.type === 'weightedAverage')?.AggFunc
        : null;
    if (weightedAvg && !weightedAvg.weightedColumnId) {
        return 'Weighted Average requires a weight column to be selected.';
    }
    return true;
};
exports.isAggregationsSectionValid = isAggregationsSectionValid;
const AggregationsSectionSummary = () => {
    const adaptable = (0, AdaptableContext_1.useAdaptable)();
    const { data: layout } = (0, OnePageAdaptableWizard_1.useOnePageAdaptableWizardContext)();
    const entries = layout.TableAggregationColumns || [];
    let content = null;
    if (entries.length) {
        content = (React.createElement(FormLayout_1.default, null, entries.map(({ ColumnId, AggFunc }) => (React.createElement(FormLayout_1.FormRow, { key: ColumnId, label: adaptable.api.columnApi.getFriendlyNameForColumnId(ColumnId) },
            React.createElement(Tag_1.Tag, null, typeof AggFunc === 'object' ? AggFunc.type : AggFunc))))));
    }
    else {
        content = React.createElement(Tag_1.Tag, null, "No Aggregations");
    }
    return React.createElement(Flex_1.Box, null, content);
};
exports.AggregationsSectionSummary = AggregationsSectionSummary;
const ColumnRow = (props) => {
    const adaptable = (0, AdaptableContext_1.useAdaptable)();
    const aggValue = props.layout?.TableAggregationColumns?.find((agg) => agg.ColumnId === props.column.columnId)?.AggFunc;
    const adaptableAggFunctions = [];
    if (props.column.dataType === 'number' && props.column.aggregatable) {
        adaptableAggFunctions.push(WEIGHTED_AVERAGE_AGG_FN_NAME);
    }
    // props.column.availableAggregationFunctions is null for non-aggregatable columns
    // but we want to support non-aggregatable columns that are specified to be aggregated by default
    // so we need to allow this. as soon as they will be unchecked from aggregation, they will no longer be displayed in the aggregation wizard.
    // but until the user checks them off, we want to allow them.
    const availableAggregationFunctions = props.column.availableAggregationFunctions || [];
    const aggOptions = [...new Set([...availableAggregationFunctions, ...adaptableAggFunctions])].map((fnName) => {
        return {
            label: fnName,
            onClick: () => {
                let aggCols = props.layout.TableAggregationColumns || [];
                if (!aggCols) {
                    return;
                }
                const AggFuncValue = fnName === WEIGHTED_AVERAGE_AGG_FN_NAME
                    ? {
                        type: 'weightedAverage',
                        weightedColumnId: null,
                    }
                    : fnName;
                let found = false;
                aggCols = aggCols.map(({ ColumnId, AggFunc }) => {
                    if (ColumnId === props.column.columnId) {
                        found = true;
                        return {
                            ColumnId,
                            AggFunc: AggFuncValue,
                        };
                    }
                    return { ColumnId, AggFunc };
                });
                if (!found) {
                    aggCols.push({
                        ColumnId: props.column.columnId,
                        AggFunc: AggFuncValue,
                    });
                }
                props.onChangeAggFunction(aggCols);
            },
        };
    });
    const numericColumnsOptions = props.numberColumns
        .filter((col) => col.columnId !== props.column.columnId)
        .map((col) => {
        return {
            label: col.friendlyName,
            onClick: () => {
                let aggCols = [...(props.layout.TableAggregationColumns || [])];
                if (!aggCols || !aggCols.length) {
                    return;
                }
                const AggFuncValue = {
                    type: 'weightedAverage',
                    weightedColumnId: col.columnId,
                };
                let found = false;
                aggCols = aggCols.map(({ ColumnId, AggFunc }) => {
                    if (ColumnId === props.column.columnId) {
                        found = true;
                        return {
                            ColumnId,
                            AggFunc: AggFuncValue,
                        };
                    }
                    return { ColumnId, AggFunc };
                });
                if (!found) {
                    aggCols.push({
                        ColumnId: props.column.columnId,
                        AggFunc: AggFuncValue,
                    });
                }
                props.onChangeAggFunction(aggCols);
            },
        };
    });
    const currentAggFnName = props.aggregationColumnsMap[props.column.columnId];
    let weightName = null;
    if (typeof aggValue === 'object' && aggValue.type === 'weightedAverage') {
        weightName = aggValue.weightedColumnId
            ? adaptable.api.columnApi.getFriendlyNameForColumnId(aggValue.weightedColumnId)
            : 'Select Weight';
    }
    return (React.createElement(Flex_1.Flex, { alignItems: "center" },
        props.column.friendlyName,
        aggValue && (React.createElement(DropdownButton_1.default, { columns: ['label'], items: aggOptions, className: "twa:ml-2" }, currentAggFnName)),
        currentAggFnName === WEIGHTED_AVERAGE_AGG_FN_NAME && (React.createElement(Flex_1.Flex, { className: "twa:bg-primary twa:ml-3", alignItems: "center" },
            React.createElement(Flex_1.Box, null, "Weight"),
            ' ',
            React.createElement(DropdownButton_1.default, { columns: ['label'], items: numericColumnsOptions, className: "twa:ml-2" }, weightName)))));
};
const AggregationsSection = (props) => {
    const adaptable = (0, AdaptableContext_1.useAdaptable)();
    const { data: layout } = (0, OnePageAdaptableWizard_1.useOnePageAdaptableWizardContext)();
    const allAggregableColumns = adaptable.api.columnApi.getAggregatableColumns();
    const allColumns = adaptable.api.columnApi.getUIAvailableColumns();
    const numberColumns = adaptable.api.columnApi.getNumericColumns();
    const allAggregatableColumnIds = allAggregableColumns.map((col) => col.columnId);
    (layout.TableAggregationColumns || []).forEach((agg) => {
        // we need to also display the columns currently aggregated,
        // even if they are not aggregatable
        if (!allAggregatableColumnIds.includes(agg.ColumnId)) {
            allAggregatableColumnIds.push(agg.ColumnId);
        }
    });
    const sortedAggregableColumns = ArrayExtensions_1.default.sortArrayWithOrder(allAggregatableColumnIds, (layout.TableAggregationColumns ?? []).map((agg) => agg.ColumnId), { sortUnorderedItems: false })
        .map((colId) => adaptable.api.columnApi.getColumnWithColumnId(colId))
        .filter(Boolean);
    const handleColumnsSelectionChange = React.useCallback((columnIds) => {
        const currentAggsMap = (layout.TableAggregationColumns || []).reduce((acc, { ColumnId, AggFunc }) => {
            acc[ColumnId] = AggFunc;
            return acc;
        }, {});
        props.onChange({
            ...layout,
            TableAggregationColumns: columnIds.map((colId) => {
                const AggFunc = currentAggsMap[colId] ?? adaptable.api.columnApi.getDefaultAggFunc(colId);
                return {
                    ColumnId: colId,
                    AggFunc,
                };
            }),
        });
    }, [layout]);
    const handleAggregationChange = React.useCallback((aggFunctions) => {
        props.onChange({
            ...layout,
            TableAggregationColumns: aggFunctions,
        });
    }, [layout]);
    const aggregationColumnsMap = React.useMemo(() => {
        const allColumnsMap = allColumns.reduce((acc, col) => {
            acc[col.columnId] = col;
            return acc;
        }, {});
        return (layout.TableAggregationColumns || []).reduce((acc, { ColumnId: colId, AggFunc }) => {
            let fn = AggFunc;
            let fnName = '';
            if (typeof fn === 'boolean') {
                fnName = allColumnsMap[colId].aggregationFunction;
            }
            if (typeof fn === 'object' && fn.type === 'weightedAverage') {
                fnName = WEIGHTED_AVERAGE_AGG_FN_NAME;
            }
            else if (typeof fn === 'string') {
                fnName = fn;
            }
            acc[colId] = fnName;
            return acc;
        }, {});
    }, [layout]);
    const handleSuppressAggFuncInHeader = (checked) => {
        props.onChange({
            ...layout,
            SuppressAggFuncInHeader: checked,
        });
    };
    return (React.createElement(Tabs_1.Tabs, { style: { height: '100%' } },
        React.createElement(Tabs_1.Tabs.Tab, null, "Column Aggregations"),
        React.createElement(Tabs_1.Tabs.Content, null,
            React.createElement(Flex_1.Flex, null,
                React.createElement(FormLayout_1.default, null,
                    React.createElement(FormLayout_1.FormRow, { label: 'Omit Aggregation from Header' },
                        React.createElement(CheckBox_1.CheckBox, { checked: layout.SuppressAggFuncInHeader, onChange: handleSuppressAggFuncInHeader })),
                    React.createElement(FormLayout_1.FormRow, { label: 'Grand Total Row' },
                        React.createElement(Select_1.Select, { style: { width: 160 }, options: ['top', 'bottom', 'pinnedTop', 'pinnedBottom'].map((position) => {
                                return {
                                    label: StringExtensions_1.default.CamelCaseToHumanText(position),
                                    value: position,
                                };
                            }), placeholder: "Off", value: layout.GrandTotalRow, onChange: (value) => {
                                props.onChange({
                                    ...layout,
                                    GrandTotalRow: value,
                                });
                            }, isClearable: true })))),
            React.createElement(ValueSelector_1.ValueSelector, { showFilterInput: true, filter: Utilities_1.columnFilter, toIdentifier: (option) => `${option.columnId}`, toLabel: (option) => option.friendlyName ?? option.columnId, toListLabel: (column) => (React.createElement(ColumnRow, { onChangeAggFunction: handleAggregationChange, layout: layout, column: column, aggregationColumnsMap: aggregationColumnsMap, numberColumns: numberColumns })), options: sortedAggregableColumns, value: (layout.TableAggregationColumns || []).map((agg) => agg.ColumnId), allowReorder: () => true, onChange: handleColumnsSelectionChange }))));
};
exports.AggregationsSection = AggregationsSection;
