import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {BehaviorSubject, Observable, Subscriber} from 'rxjs';
import {Affiliation} from '../../utils/entities/CuratorInfo';
import {properties} from "../../../../environments/environment";
import {AdvancedAsyncSubject} from "../../utils/AdvancedAsyncSubject";

@Injectable()
export class AffiliationService {
  
  private affiliationsSubject: BehaviorSubject<Affiliation[]> = new BehaviorSubject([]);
  sub;
  
  constructor(private http: HttpClient) {
  }
  
  ngOnDestroy() {
    this.clearSubscriptions();
  }
  
  clearSubscriptions() {
    if (this.sub instanceof Subscriber) {
      this.sub.unsubscribe();
    }
  }
  
  public initAffiliations(communityId: string): void {
    this.sub = this.getAffiliations(communityId).subscribe((affiliations) => {
        this.affiliationsSubject.next(affiliations);
      },
      error => {
        this.affiliationsSubject.error(error);
      });
  }
  
  public get affiliations(): Observable<Affiliation[]> {
    return this.affiliationsSubject.asObservable();
  }
  
  public getAffiliations(communityId: string): Observable<Affiliation[]> {
    let url = properties.communityAPI + communityId + "/organizations";
    return this.http.get<Affiliation[]>((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url);
  }
  
  public updateAffiliation(url: string, affiliation: Affiliation) {
    let headers = new HttpHeaders({'Content-Type': 'application/json', 'accept': 'application/json'});
    return this.http.post<Affiliation>(url, JSON.stringify(affiliation), {headers: headers});
  }
  
  public deleteAffiliation(url: string, id: string) {
    let headers = new HttpHeaders({'Content-Type': 'application/json', 'accept': 'application/json'});
    return this.http.request('delete', url, {body: id, headers: headers})
  }
  
}
