import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {environment} from '../../../environments/environment';
import {HttpClient} from '@angular/common/http';
import {map} from 'rxjs/operators';

@Injectable()
export class SocServiceService {

  private socServices$: BehaviorSubject<any[]>;

  constructor(private http: HttpClient) {
  }

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

  public clearSocServices() {
    this.socServices$ = null;
  }

  public getSocServices$(): Observable<any> {
    if (this.socServices$) {
      return this.socServices$;
    }

    this.socServices$ = new BehaviorSubject<any[]>([]);
    return this.queryFromServer()
      .pipe(map((response: any[]) => {
        this.socServices$.next(response);
        return this.socServices$.getValue() as any[];
      }));
  }

  public storeSocService(data: any): Observable<any> {
    const qstring = environment.api + '/soc-service/store';
    return this.http.post(qstring, data)
      .pipe(map((response: any) => {
        this.clearSocServices();
        return response as any;
      }));
  }

  public deleteSocService(socServiceId: number) {
    const qstring = environment.api + '/soc-service/delete/' + socServiceId.toString();
    return this.http.get(qstring)
      .pipe(map((response: any) => {
        this.clearSocServices();
        return response as any;
      }));
  }
}
