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

@Injectable()
export class ParameterService {

  private parameters$: BehaviorSubject<any[]>;

  constructor(private http: HttpClient) {
  }

  public getParameters$() {
    if (!this.parameters$) {
      this.parameters$ = new BehaviorSubject<any[]>([]);
      this.queryParametersFromServer()
        .subscribe(response => this.parameters$.next(response));
    }

    return this.parameters$;
  }

  public clearParameters() {
    this.parameters$ = null;
  }

  private queryParametersFromServer(): Observable<any[]> {

    const qstring = environment.api + '/parameter/all';

    return this.http.get(qstring)
      .pipe(map((response: any) => {
        return response as any[];
      }));
  }

  public storeParameters(data: any): Observable<any[]> {

    const qstring = environment.api + '/parameter/store';

    return this.http.post(qstring, data)
      .pipe(map((response: any) => {
        return response as any[];
      }));
  }
}
