import {Component} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Meta, Title} from '@angular/platform-browser';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';

import {PiwikService} from '../openaireLibrary/utils/piwik/piwik.service';
import {User} from '../openaireLibrary/login/utils/helper.class';
import {StringUtils} from '../openaireLibrary/utils/string-utils.class';

import {ErrorCodes} from '../openaireLibrary/utils/properties/errorCodes';
import {ErrorMessagesComponent} from '../openaireLibrary/utils/errorMessages.component';
import {HelperService} from "../openaireLibrary/utils/helper/helper.service";
import {SEOService} from "../openaireLibrary/sharedComponents/SEO/SEO.service";
import {UserManagementService} from "../openaireLibrary/services/user-management.service";
import {Breadcrumb} from "../openaireLibrary/utils/breadcrumbs/breadcrumbs.component";
import {properties} from "../../environments/environment";
import {Subscriber} from "rxjs";
import {StakeholderService} from "../openaireLibrary/monitor/services/stakeholder.service";
import {StakeholderEntities, StakeholderInfo} from "../openaireLibrary/monitor/entities/stakeholder";

@Component({
  selector: 'my-stakeholders',
  templateUrl: 'my-stakeholders.component.html',
})

export class MyStakeholdersComponent {
	public stakeholderEntities = StakeholderEntities;
  public pageTitle = "OpenAIRE | My " + this.stakeholderEntities.STAKEHOLDERS;
  public description = "OpenAIRE - Monitor, A new era of monitoring research. Open data. Open methodologies | My managing and member of " + this.stakeholderEntities.STAKEHOLDERS;
  public stakeholders: StakeholderInfo[] = [];
  public pageContents = null;
  public divContents = null;
  // Message variables
  public status: number;
  public loading: boolean = true;
  public subscriberErrorMessage: string = "";
  public errorCodes: ErrorCodes;
  private errorMessages: ErrorMessagesComponent;
  public breadcrumbs: Breadcrumb[] = [{name: 'home', route: '/'}, {name: 'My ' + this.stakeholderEntities.STAKEHOLDERS}];
  public properties: EnvProperties = properties;
  private user: User;
  private subscriptions = [];
  
  constructor(
    private route: ActivatedRoute,
    private _router: Router,
    private _meta: Meta,
    private _title: Title,
    private _piwikService: PiwikService,
    private stakeholderService: StakeholderService,
    private helper: HelperService,
    private seoService: SEOService,
    private userManagementService: UserManagementService) {
    this._meta.updateTag({content: this.description}, "name='description'");
    this._meta.updateTag({content: this.description}, "property='og:description'");
    this._meta.updateTag({content: this.pageTitle}, "property='og:title'");
    this._title.setTitle(this.pageTitle);
    this.errorCodes = new ErrorCodes();
    this.errorMessages = new ErrorMessagesComponent();
    this.status = this.errorCodes.LOADING;
  }
  
  public ngOnInit() {
    var url = this.properties.domain + this.properties.baseLink + this._router.url;
    this.seoService.createLinkForCanonicalURL(url, false);
    this._meta.updateTag({content: url}, "property='og:url'");
    this.subscriptions.push(this._piwikService.trackView(this.properties, "OpenAIRE Connect").subscribe());
    this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
      this.user = user;
      if (this.user) {
        this.getStakeholders();
      }
      //this.getDivContents();
      //this.getPageContents();
    }));
    
  }
  
  private getPageContents() {
    this.subscriptions.push(this.helper.getPageHelpContents(this.properties, 'connect', this._router.url).subscribe(contents => {
      this.pageContents = contents;
    }));
  }
  
  private getDivContents() {
    this.subscriptions.push(this.helper.getDivHelpContents(this.properties, 'connect', this._router.url).subscribe(contents => {
      this.divContents = contents;
    }));
  }
  
  get manager(): StakeholderInfo[] {
    return (this.stakeholders)?this.stakeholders.filter(stakeholder => stakeholder.isManager):[];
  }
  
  get member(): StakeholderInfo[] {
    return (this.stakeholders)?this.stakeholders.filter(stakeholder => stakeholder.isMember):[];
  }
  
  public getStakeholders() {
    this.loading = true;
    this.status = this.errorCodes.LOADING;
    this.subscriberErrorMessage = "";
    this.stakeholders = [];
    this.subscriptions.push(this.stakeholderService.getMyStakeholders(properties.monitorServiceAPIURL).subscribe(
      stakeholders => {
          this.stakeholders = StakeholderInfo.toStakeholderInfo(stakeholders, this.user);
          this.sort(this.stakeholders);
          this.loading = false;
      },
      error => {
        this.status = this.handleError("Error getting communities", error);
        this.loading = false;
      }
    ));
  }
  
  private sort(results: StakeholderInfo[]) {
    results.sort((left, right): number => {
      if (left.name > right.name) {
        return 1;
      } else if (left.name < right.name) {
        return -1;
      } else {
        return 0;
      }
    })
  }
  
  public quote(param: string): string {
    return StringUtils.quote(param);
  }
  
  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }
  
  private handleError(message: string, error): number {
    let code = "";
    if (!error.status) {
      code = error.code;
    } else {
      code = error.status;
    }
    console.error("Communities (component): " + message, error);
    return this.errorMessages.getErrorCode(code);
  }
}
