import { Component, OnInit } from '@angular/core';
import {Observable, Subscriber} from 'rxjs';
import {TypeOfLoansModel} from '../models/type-of-loans.model';
import {HttpClient} from '@angular/common/http';
import {AuthService} from '../service/auth.service';
import {map} from 'rxjs/operators';
import {equalsArray, randomNumber} from '../helper.function';

@Component({
  selector: 'app-chart-type-of-loans',
  templateUrl: './chart-type-of-loans.component.html',
  styleUrls: ['./chart-type-of-loans.component.scss']
})
export class ChartTypeOfLoansComponent implements OnInit {
  public autoFit = true;
  // public data: Observable<TypeOfLoansModel[]>;
  public data: Observable<TypeOfLoansModel[]>;

  public totalNumberOfLoans = 0;

  constructor(private auth: AuthService, private http: HttpClient) { }

  private previous: TypeOfLoansModel[] = [];
  ngOnInit(): void {
    this.data = new Observable<TypeOfLoansModel[]>( (observer) => {
      this.updateTypeOfLoans(observer);
    });
  }

  public labelContent(e: any): string {
    return e.dataItem.Count + ' ' + e.category + ' (' + + (e.dataItem.Share * 100).toFixed(2) + '%' + ')' ;
  }

  public updateTypeOfLoans(observer: Subscriber<TypeOfLoansModel[]>): void {
    this.getTypeOfLoans().subscribe(
      resp => {
        if ( ! equalsArray(this.previous, resp ) ){
          this.previous = resp;
          this.totalNumberOfLoans = 0;
          resp.reduce( (acc, curr)  => {
            this.totalNumberOfLoans += curr.Count;
            return acc;
          });
          observer.next(resp);
        }
     });
    const refresh = randomNumber(3000, 6000);
    setTimeout( () => {
      // this.updateTypeOfLoans(observer);
    }, refresh);
  }

  public getTypeOfLoans(): Observable<TypeOfLoansModel[]> {
    return this.http.get<TypeOfLoansModel[]>(this.auth.getUrl('chart/type-of-loans')).pipe(
      map(
        input => {
          const ret = [];
          if (Array.isArray(input)) {
            input.forEach( (value, index) =>{
              ret.push({
                Kind: value.Kind,
                Count: value.Count,
                Share: value.Share,
                Amount: value.Amount
              });
            });
          }
          return ret;
        }
      )
    );
  }

}
