import { FarrisDataState } from './farris-dataitem'; import { BehaviorSubject, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; export class BaseDataFacadeService { protected _state = this._initState; disableExpress: (item) => boolean; readonly store = new BehaviorSubject(this._state); readonly state$ = this.store.asObservable(); data$: Observable = this.state$.pipe(map((state: T) => state.data)); constructor(private _initState: T) { } private initData(data: any) { return data.map(d => { const _id = d[this._state.idField]; const disable = () => { return this.disableExpress ? this.disableExpress(d) : false; }; return { id: _id, data: d, disabled: disable(), }; }); } protected updateState(state: any) { const newState = {...this._state, ...state}; this.store.next(this._state = newState); } initState(state: any) { this.updateState(state); } isSelect(id: any) { if (this._state.selections && this._state.selections.length) { return this._state.selections.find(item => !!item ? item[this._state.idField] == id : false) !== undefined; } return false; } loadData(data: any, selectValues: string = '', separator = ',') { if (data) { const _data = this.initData(data); this.updateState({...this._state, data: _data}); if (selectValues) { this.setSelections(selectValues, separator); } else { this._state.selections = []; } } else { this.updateState({ data: [], selections: [] }); } } getSelections() { return this._state.selections; } setSelections(selectValues: string, separator = ',') { if (selectValues) { let selectedItems = []; if (this._state.multiSelect) { selectedItems = selectValues.split(separator).map( val => { return this._state.data.find(d => d.data[this._state.valueField] + '' == val); }).map( n => { return n ? n.data : ''; }).filter(n => n); } else { selectedItems = [this._state.data.find(d => d.data[this._state.valueField] + '' == selectValues)]; } this.updateState({selections: selectedItems }); } } selectAll() { this.updateState({selections: this._state.data.map(n => n.data) }); } unSelectAll() { this.clearSelections(); } selectItem(data: any, index?: number) { const idfield = this._state.idField; let selections = this.getSelections(); const id = data[idfield]; if (!this._state.multiSelect) { if (!this.isSelect(id)) { selections = [ data ]; } } else { if (!this.isSelect(id)) { selections.push(data); } } const items = this.cloneArray(selections); this.updateState({selections: items}); } unSelectItem(data: any) { const idfield = this._state.idField; let selections = this.getSelections(); const id = data[idfield]; if (!this._state.multiSelect) { selections = []; } else { selections = selections.filter(n => n[idfield] != id) ; } const items = this.cloneArray(selections); this.updateState({selections: items}); } clearSelections() { this.updateState({selections: []}); } private cloneArray(arr: any[]) { if (arr && arr.length) { return arr.map( n => n); } return arr; } }