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

@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, private config: ConfigurationService) {
  }
  
  public ngOnInit() {
    this.subscriptions.push(this.config.portalAsObservable.subscribe(
      res => {
        // this.portal = res;
        this.communityId = res.pid
      },
      error => {
        console.log(error);
      }
    ));
    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();
  }
}
