import { BehaviorSubject, combineLatest, Observable, Subject } from "rxjs";
import {
debounceTime,
distinctUntilChanged,
map,
shareReplay,
startWith,
takeUntil,
} from "rxjs/operators";
import { OnDestroy, EventEmitter, Injectable } from "@angular/core";
import { NgUnsubscribe } from "../../../ng-unsubscribe";
import {
Column,
DataListConfiguration,
SelectionParams,
} from "../../interfaces/list.interfaces";
import { IgxGridCell } from "@infragistics/igniteui-angular";
import { DataListApi } from "../data-list.api";
@Injectable()
export class DataListActionsService implements OnDestroy {
private _unsubscribe = NgUnsubscribe.create();
constructor() {}
public mapSelectionState(
total,
selectedItems: Observable<SelectionParams>,
link,
islands,
columnObservable: Observable<Column>,
cellObservable: Observable<IgxGridCell>,
grid,
api: DataListApi,
exportEmitter: EventEmitter<any>
) {
if (!api || !grid) {
console.error("api && grid are required for initialization");
return;
}
return combineLatest(
total.pipe(startWith(0)),
selectedItems.pipe(startWith(null)),
link.pipe(startWith(null), distinctUntilChanged()),
columnObservable,
cellObservable
).pipe(
debounceTime(1),
map(([total, selection, link, column, cell]) => {
const data: any = {
total,
link,
column,
cell,
grid,
api,
export: exportEmitter,
};
if (!selection) {
data.total = 0;
data.selected = 0;
return data;
}
data.selected = selection.count || 0;
data.selection = selection;
if (data.selection.treeSelections) {
Object.keys(data.selection.treeSelections).forEach((key) => {
data[key] = data.selection.treeSelections[key];
});
}
data.childrenSelected = 0;
let dataChildren: { [index: string]: number } = {};
data.children = dataChildren;
if (selection && selection["children"]) {
Object.keys(selection["children"]).forEach((islandKey) => {
let children = selection["children"][islandKey];
dataChildren[islandKey] = 0;
Object.keys(children).forEach((parentKey) => {
dataChildren[islandKey] += children[parentKey].count;
});
data.childrenSelected = dataChildren[islandKey];
});
data.childrenSelection = selection["children"];
}
// ensure, that all islands are registered with a zero count
// this should make interpolation of custom strings of the selection
// count easier
if (islands.length > 0) {
islands.forEach((islandKey) => {
if (data.children.hasOwnProperty(islandKey)) {
return;
}
data.children[islandKey] = 0;
});
}
return data;
})
);
}
ngOnDestroy(): void {
this._unsubscribe.destroy();
}
}