import { ColumnState } from "ag-grid-community";
import { BindableProperty, HtmlBehaviorResource, metadata } from "aurelia-framework";
import { GridOptions } from "./../resources/elements/utilities/ag-grid-helpers";
import { CustomColDef } from "./../model/common-model";

export function generateBindables(names: string[], bindingModeToUse?: any): any {
    return function (target: any, key: any, descriptor: any) {
        // get or create the HtmlBehaviorResource
        // on which we're going to create the BindableProperty's
        let behaviorResource: HtmlBehaviorResource = <HtmlBehaviorResource>metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, target);

        let nameOrConfigOrTargets: any[] = names.map((name) => {
            let nameOrConfigOrTarget: any = {
                name: name
            };

            if (bindingModeToUse) {
                nameOrConfigOrTarget["defaultBindingMode"] = bindingModeToUse;
            }

            return nameOrConfigOrTarget;
        });

        nameOrConfigOrTargets.forEach((nameOrConfigOrTarget) => {
            let prop = new BindableProperty(nameOrConfigOrTarget);
            prop.registerWith(target, behaviorResource, descriptor);
        });
    };
};

export function getNewColumnStates(gridOptions: GridOptions, newStates: ColumnState[]): ColumnState[] {
    let columnDefs = gridOptions.api.getColumnDefs();
    let currentStates = gridOptions.columnApi.getColumnState();
    let resultStates: ColumnState[] = [];
    //Pinned from current and non existing in new from current
    for (const currentState of currentStates) {
        if (!newStates.some(n => n.colId == currentState.colId)) {
            let colDef: CustomColDef = columnDefs.find((x: CustomColDef) => x.colId == currentState.colId);
            if (colDef?.viewMovable === false) {
                resultStates.push(currentState);
            }
        }
    }
    //New not already in result
    resultStates.push(...newStates.filter(c => !resultStates.some(n => n.colId == c.colId)));
    return resultStates;
}

export function autoAdjustColumnsSize(gridOptions: GridOptions) {
    if (gridOptions.adjustColumns === true) {
        gridOptions.api.sizeColumnsToFit();
    } else {
        gridOptions.columnApi.autoSizeAllColumns();
    }
}