import { DataSource } from '@angular/cdk/table';

import { BehaviorSubject, Observable, merge } from 'rxjs';
import { map } from 'rxjs/operators';

import { CollectionViewer } from '@angular/cdk/collections';

import { BankInfo } from 'src/modules/sites/bank-info/model/bank-info.model';
import { BankInfoService } from 'src/modules/sites/bank-info/service/bank-info.service';

import { FormControl, FormGroup, Validators, FormArray } from '@angular/forms';

export class BankInfoListDataSource extends DataSource<BankInfo> {
  private _objectStore: BankInfo[] = [];
  private _ObjectsSubject$ = new BehaviorSubject<BankInfo[]>([]);
  private _loadingSubject$ = new BehaviorSubject<boolean>(false);

  public loading$ = this._loadingSubject$.asObservable();
  public formg: FormGroup;

  constructor(private bankInfoService: BankInfoService) {
    super();
  }

  connect(collectionViewer: CollectionViewer): Observable<BankInfo[]> {
    return this.bankInfoService.getAllAsFormArray().pipe(
      map(res => {
        res.forEach(m => this._objectStore.push(m as BankInfo));
        this._ObjectsSubject$.next(this._objectStore);
        let fa = <FormArray>this.formg.get('formarray');
        res.forEach(r => fa.push(this.createRowFormGroup(r)));
        return res;
      })
    );
  }

  createRowFormGroup(r: BankInfo): FormGroup {
    let f = new FormGroup({
      id: this.createNewFormContorl(r, 'id'),
      name: this.createNewFormContorl(r, 'name'),
      number: this.createNewFormContorl(r, 'number'),
      holder: this.createNewFormContorl(r, 'holder'),
      description: this.createNewFormContorl(r, 'description')
    });
    return f;
  }

  createNewFormContorl(r: BankInfo, propName: string): FormControl {
    let m = new FormControl(r[propName], Validators.required);
    m.valueChanges.subscribe(val => {
      r[propName] = val;
    });
    return m;
  }

  disconnect(collectionViewer: CollectionViewer): void {
    this._ObjectsSubject$.complete();
    this._loadingSubject$.complete();
  }
}
