import {Component} from '@angular/core';
import {SearchCustomFilter} from "../../../openaireLibrary/searchPages/searchUtils/searchUtils.class";
import {ActivatedRoute, Router} from "@angular/router";
import {StakeholderService} from "../../../openaireLibrary/monitor/services/stakeholder.service";
import {Subscriber} from "rxjs";
import {ConfigurationService} from "../../../openaireLibrary/utils/configuration/configuration.service";

@Component({
  selector: 'monitor-search-dataproviders',
  template: `
    <div id="page_content">
      <search-dataproviders *ngIf="initialized"
                            [customFilter]=customFilter [hasPrefix]="false"
                            [includeOnlyResultsAndFilter]="false" [showSwitchSearchLink]="showSwitchSearchLink" [piwikSiteId]="piwikSiteId">
      </search-dataproviders>
    </div>
  `
})
export class MonitorSearchDataprovidersComponent {
  customFilter: SearchCustomFilter = null;
  initialized: boolean = false;
  showSwitchSearchLink:boolean = false;
  piwikSiteId;
  constructor(private route: ActivatedRoute,
              private router: Router,
              private stakeholderService: StakeholderService,  private configurationService: ConfigurationService) {
  }
  subscriptions = [];
  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }

  ngOnInit() {
    this.subscriptions.push(this.route.params.subscribe(params => {
      if (params['stakeholder']) {
        this.subscriptions.push(this.stakeholderService.getStakeholderAsObservable().subscribe(stakeholder => {
          if (stakeholder) {
            if (stakeholder.type === "funder") {
              this.navigateToError();
            } else if (stakeholder.type === "organization") {
              let value = stakeholder.index_id;
              this.customFilter = new SearchCustomFilter("Organization", "relorganizationid", value, "");
            } else if (stakeholder.type === "ri") {
              this.navigateToError();
            }
            this.subscriptions.push(this.configurationService.communityInformationState.subscribe(portal => {
              if (portal) {
                this.piwikSiteId = portal.piwik;
              }
            }));
            this.initialized = true;
          }
        }));
      }
    }));
  }
  
  navigateToError() {
    this.router.navigate(['/error'], {queryParams: {'page': this.router.url}});
  }
}
