import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {Router} from '@angular/router';
import {LookupSourceService} from './lookup-source.service';
import {environment} from '../../../environments/environment';
import {map} from 'rxjs/operators';

@Injectable()
export class SupplierService {

  private suppliers$: BehaviorSubject<any[]>;

  constructor(private http: HttpClient) {
  }

  public getSuppliers$() {
    if (!this.suppliers$) {
      this.suppliers$ = new BehaviorSubject<any[]>([]);
      this.queryFromServer()
        .subscribe(response => this.suppliers$.next(response));
    }

    return this.suppliers$;
  }

  public clearSuppliers() {
    this.suppliers$ = null;
  }

  private queryFromServer(): Observable<any[]> {
    const qstring = environment.api + '/supplier/all';
    return this.http.get(qstring)
      .pipe(map((response: any) => {
        return response as any[];
      }));
  }

  public getSupplierById(id: number): Observable<any> {
    return this.getSuppliers$().getValue().find(supplier => supplier.id === id);
  }

  public storeSupplier(data: any): Observable<any> {
    const qstring = environment.api + '/supplier/store';
    return this.http.post(qstring, data)
      .pipe(map((response: any) => {
        this.clearSuppliers();
        return response as any;
      }));
  }

  public deleteSupplier(supplierId: number) {
    const qstring = environment.api + '/supplier/delete/' + supplierId;
    return this.http.get(qstring)
      .pipe(map((response: any) => {
        this.clearSuppliers();
        return response as any;
      }));
  }
}
