import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { CachingService } from "./caching.service";
import { tap } from 'rxjs/operators';

@Injectable({ providedIn: "root" })
export class ClientService extends CachingService {
  constructor(private readonly http: HttpClient) {
    super("clients");
  }

  public getClients(filters = {}) {
    this.request(
      this.http.get<any>("/api/clients", { params: filters })
    );
    return this.getStream();
  }

  public getClientById(id: number) {
    this.request(this.http.get<any>(`/api/clients/${id}`));
    return this.getStream(id);
  }

  public updateClient(clientInfo) {
    const { id } = clientInfo;

    this.request(this.http.put(`/api/clients/${id}`, clientInfo));
    return this.getStream(id);
  }

  public addClient(clientInfo) {
    this.request(this.http.post(`/api/clients/`, clientInfo));
    return this.http.post(`/api/clients/`, clientInfo);
  }

  public addInterest(clientId, interest) {
    for (let i in interest) {
      if (interest[i] == undefined || interest[i] == null || interest[i] == '') delete interest[i];
    }

    if (!clientId)
      throw new Error("Client is not submitted!");

    return this.http.post(`/api/clients/${clientId}/interests`, interest).pipe(
      tap(client => this.updateId(clientId, client))
    );
  }
}
