import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {CommunityInfo} from './communityInfo';
import {map} from "rxjs/operators";
import {BehaviorSubject, from, Observable, Subscriber} from "rxjs";
import {properties} from "../../../../environments/environment";
import {StringUtils} from "../../utils/string-utils.class";
import {SelectionCriteria} from "../../utils/entities/contentProvider";

@Injectable({providedIn: 'root'})
export class CommunityService {
  
  public community: BehaviorSubject<CommunityInfo> = new BehaviorSubject(null);
  public communityId: string = null;
  private promise: Promise<void> = null;
  private subs = [];
  
  constructor(private http: HttpClient) {}
  
  clearSubscriptions() {
    this.subs.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }
  
  public getCommunityAsObservable() {
    return this.community.asObservable();
  }
  
  setCommunity(community: CommunityInfo) {
    this.community.next(community);
  }
  
  getCommunityInfo(communityId: string) {
    return this.http.get<CommunityInfo>(properties.communityAPI + communityId)
      .pipe(map(community => this.parseCommunity(community)));
  }
  
  getCommunity(communityId: string, refresh = false) {
    if (this.communityId !== communityId || !this.community.value || refresh) {
      this.communityId = communityId;
      this.promise = new Promise<void>((resolve, reject) => {
        this.subs.push(this.getCommunityInfo(communityId).subscribe(community => {
              this.community.next(community);
              resolve();
            },
            error => {
              this.community.next(null);
              resolve();
            }));
      });
    }
    return from(this.getCommunityAsync());
  }
  
  async getCommunityAsync() {
    await this.promise;
    // this.clearSubscriptions();
    return this.community.getValue();
  }
  
  updateCommunity(url: string, community: any) {
    if (!community.logoUrl) {
      community.logoUrl = '';
    }
    const options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
      })
    };
    return this.http.post(url, community, options);
  }
  
  public updateSubjects(subjects: string[], fos: string[], sdg: string[]) {
    let communityInfo: CommunityInfo = this.community.value;
    communityInfo.subjects = subjects;
    communityInfo.fos = fos;
    communityInfo.sdg = sdg;
    this.community.next(communityInfo);
  }
  
  public updateAdvancedCriteria(selectionCriteria: SelectionCriteria) {
    let communityInfo: CommunityInfo = this.community.value;
    communityInfo.selectionCriteria = selectionCriteria;
    this.community.next(communityInfo);
  }
  
  public parseCommunity(data: any): CommunityInfo {
    const resData = Array.isArray(data) ? data[0] : data;
    const community: CommunityInfo = new CommunityInfo();
    community.title = resData.name;
    community.shortTitle = resData.shortName;
    community.communityId = resData.id;
    community.queryId = resData.queryId;
    community.logoUrl = resData.logoUrl;
    community.description = resData.description;
    community.date = resData.creationDate;
    community.zenodoCommunity = resData.zenodoCommunity;
    community.status = 'PUBLIC';
    community.claim = resData.claim;
    community.membership = resData.membership;
    community.type = resData.type;
    community.otherZenodoCommunities = resData.otherZenodoCommunities;
    if (resData.hasOwnProperty('status')) {
      community.status = resData.status;
      community.validateStatus();
    }
    if (resData.subjects != null) {
      community.subjects = Array.isArray(resData.subjects)?resData.subjects:[resData.subjects];
    } else {
			community.subjects = [];
		}
		if (resData.sdg != null) {
      community.sdg = Array.isArray(resData.sdg)?resData.sdg:[resData.sdg];
    } else {
			community.sdg = [];
		}
		if (resData.fos != null) {
      community.fos = Array.isArray(resData.fos)?resData.fos:[resData.fos];
    } else {
			community.fos = [];
		}
    if (resData.advancedConstraints != null) {
      community.selectionCriteria = resData.advancedConstraints;
    } else {
      community.selectionCriteria = new SelectionCriteria();
    }
    return CommunityInfo.checkIsUpload(community);
  }
  
  isRIType(community: string): Observable<boolean> {
    return this.getCommunity(community).pipe(map(community => community.type === 'ri'));
  }
  
  isCommunityType(community: string): Observable<boolean> {
    return this.getCommunity(community).pipe(map(community => community.type === 'community'));
  }
}
