import { Component, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { EnvProperties} from '../../utils/properties/env-properties';

import {ConnectHelper} from '../connectHelper';
import {SearchCommunityDataprovidersService} from '../contentProviders/searchDataproviders.service';
import {properties} from "../../../../environments/environment";
import {OpenaireEntities} from "../../utils/properties/searchFields";

@Component({
    selector: 'approved-by-community',
    template: `
      <span *ngIf="approved" class="uk-align-right uk-label custom-label uk-label-success">{{openaireEntities.COMMUNITY}} Approved</span>
    `
})

export class ApprovedByCommunityComponent {
  @Input() contentProviderId: string;

  public communityId:string;
  public approved:boolean = false;
  private communityContentProviders = [];

  properties:EnvProperties;
  public openaireEntities = OpenaireEntities;

  constructor (private route: ActivatedRoute, private _searchDataprovidersService: SearchCommunityDataprovidersService) {}

    public ngOnInit() {
      this.properties =properties;
       this.route.queryParams.subscribe(
         communityId => {
             this.communityId  = ConnectHelper.getCommunityFromDomain(this.properties.domain);
             if(!this.communityId) {
               this.communityId = communityId['communityId'];
             }

              if(this.communityId && this.communityId != "openaire") {
                this._searchDataprovidersService.searchDataproviders(this.properties, this.communityId).subscribe (
                    contentproviders => {
                       this.communityContentProviders = contentproviders;
                       this.approved = this.checkApproval();
                    },
                    error => {
                        this.handleError("Error getting "+OpenaireEntities.DATASOURCES+" for "+OpenaireEntities.COMMUNITY+" with id: "+this.communityId, error);
                    }
                );
              }
          });



    }

    private checkApproval(): boolean {
      let self = this;
      return this.communityContentProviders.map(contentprovider => contentprovider.openaireId).some(function(id) {
        return id == self.contentProviderId;
      });
    }

    private handleError(message: string, error) {
        console.error("Approved by "+OpenaireEntities.COMMUNITY+" (component): "+message, error);
    }
}
