import {Component, Input} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
import {AffiliationService} from "../openaireLibrary/connect/affiliations/affiliation.service";
import {Affiliation} from "../openaireLibrary/utils/entities/CuratorInfo";
import {ConnectHelper} from "../openaireLibrary/connect/connectHelper";
import {Subscriber} from "rxjs";
import {properties} from "../../environments/environment";

@Component({
  selector: 'affiliations',
  templateUrl: './affiliations.component.html',
  styleUrls: ['./affiliations.component.less']
})
export class AffiliationsComponent {
  @Input() getAffiliationsFromAPI: boolean = false;
  @Input() longView: boolean = false;
  @Input() communityFirstPage: boolean = false;
  @Input() affiliationsInSlider: number = 5;
  @Input() affiliations: Affiliation[] = [];
  @Input() sliderOptions = '';
  @Input() arrows = true;
  
  public showLoading: boolean = false;
  public communityId: string;
  public properties: EnvProperties = properties;
  private subscriptions = [];
  
  constructor(private route: ActivatedRoute, private affiliationService: AffiliationService) {
  }
  
  public ngOnInit() {
    this.communityId = ConnectHelper.getCommunityFromDomain(properties.domain);
    if (this.getAffiliationsFromAPI) {
      this.showLoading = true;
      this.affiliationService.initAffiliations(this.communityId);
      this.subscriptions.push(this.affiliationService.affiliations.subscribe(
        affiliations => {
          this.affiliations = affiliations.filter((affiliation) => this.longView || !!affiliation['logo_url']);
          this.showLoading = false;
        },
        error => {
          console.error("Affiliations Component: Error getting affiliations for community with id: " + this.communityId, error);
          this.showLoading = false;
        }
      ));
    }
  }
  
  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
    this.affiliationService.clearSubscriptions();
  }
}
