import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { GridDataResult } from '@progress/kendo-angular-grid';
import { Observable, BehaviorSubject } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import {AuthService} from './auth.service';

export abstract class LoanQueryService extends BehaviorSubject<GridDataResult> {
  public loading: boolean;

  private BASE_URL = '';

  protected constructor(
    private http: HttpClient,
    private auth: AuthService,
    protected tableName: string
  ) {
    super(null);
    this.BASE_URL = this.auth.getUrl('grid/loan/');
  }

  public query(state: any): void {
    this.fetch(this.tableName, state)
      .subscribe(x => super.next(x));
  }

  protected fetch(tableName: string, state: any): Observable<GridDataResult> {
    // const queryStr = `${toODataString(state)}&$count=true`;
    this.loading = true;

    return this.http
      .post<GridDataResult>(`${this.BASE_URL}${tableName}`, state)
      .pipe(
        map(response => {
          response.data.forEach( (value, index) =>{
              response.data[index].Settlement = this.convertToDateTimeObject(value.Settlement);
              response.data[index].LastPayInDate = this.convertToDateTimeObject(value.LastPayInDate);
              // console.log(index, response.data[index].Settlement , typeof response.data[index].Settlement );
              // console.log(index, response.data[index].LastPayInDate , typeof response.data[index].LastPayInDate );
          });
          // console.log(response);
          return response;
        }),
        tap(() => this.loading = false)
      );
  }

  public convertToDateTimeObject(str: string): Date{
    if (str === '0001-01-01T00:00:00Z' || str === ''){
      return null; // new Date('1900-12-31T13:00:00.000Z');
    }else{
      return new Date(str);
    }
  }
}

@Injectable()
export class LoanSummaryService extends LoanQueryService {
  constructor(http: HttpClient, auth: AuthService) { super(http, auth, 'full-loan-overview'); }

  queryAll(st?: any): Observable<GridDataResult> {
    const state = Object.assign({}, st);
    delete state.skip;
    delete state.take;

    return this.fetch(this.tableName, state);
  }
}
