import {EnvProperties} from '../../openaireLibrary/utils/properties/env-properties';
import {ZenodoCommunitiesService} from '../../openaireLibrary/connect/zenodoCommunities/zenodo-communities.service';
import {SearchZenodoCommunitiesService} from '../../openaireLibrary/connect/zenodoCommunities/searchZenodoCommunities.service';

import {ZenodoInformationClass} from '../../openaireLibrary/deposit/utils/zenodoInformation.class';
import {Subscriber} from "rxjs";
import {Injectable} from "@angular/core";

@Injectable({
  providedIn: 'root'
})
export class FetchZenodoInformation {
  private subscriptions = [];
  constructor ( private _zenodoCommunitieService: ZenodoCommunitiesService,
                private _searchZenodoCommunitiesService: SearchZenodoCommunitiesService  ) { }

  public ngOnDestroy() {
    this.clearSubscriptions();
  }

  clearSubscriptions(){
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }
  public getZenodoCommunityNameAndUrlById(masterZenodoCommunityId: string, properties:EnvProperties, zenodoInformation: ZenodoInformationClass){
    this.subscriptions.push(this._zenodoCommunitieService.getZenodoCommunityById(properties, properties.zenodoCommunities+masterZenodoCommunityId, null).subscribe(
      result  => {
        console.info("getZenodoCommunityNameAndUrlById", result);
        var masterZenodoCommunity = result;
        //zenodoInformation.name = masterZenodoCommunity.title;
        zenodoInformation.url = masterZenodoCommunity.link;
      },
      error => {
        console.error("Master Zenodo community'"+masterZenodoCommunityId+"' couldn't be loaded");
      }
    ));
  }

  public searchNumberOfZCommunities(communityId: string, properties: EnvProperties, zenodoInformation: ZenodoInformationClass) {
    this.subscriptions.push(this._searchZenodoCommunitiesService.searchZCommunities(properties,communityId).subscribe (
      result => {
        console.info("searchNumberOfZCommunities", result);

        var CommunityIds = result;
            var totalResults = CommunityIds.length;
            if(totalResults > 0) {
              zenodoInformation.shareInZenodoUrl = properties.shareInZenodoPage;
              console.info(zenodoInformation.shareInZenodoUrl);
            }
      },
      error => {
        console.error("list of zenodo communities couldn't be loaded");
      }
    ));
  }
}
