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 {ZenodoCommunitiesService} from '../../openaireLibrary/connect/zenodoCommunities/zenodo-communities.service';
import {CommunityService} from '../../openaireLibrary/connect/community/community.service';
import {CommunityInfo} from '../../openaireLibrary/connect/community/communityInfo';
import {SearchUtilsClass} from '../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
import {ErrorCodes} from '../../openaireLibrary/utils/properties/errorCodes';
import {HelperService} from "../../openaireLibrary/utils/helper/helper.service";
import {RouterHelper} from "../../openaireLibrary/utils/routerHelper.class";
import {SEOService} from "../../openaireLibrary/sharedComponents/SEO/SEO.service";
import {PiwikService} from "../../openaireLibrary/utils/piwik/piwik.service";
import {Breadcrumb} from "../../openaireLibrary/utils/breadcrumbs/breadcrumbs.component";
import {properties} from "../../../environments/environment";
import {Subscriber, Subscription} from "rxjs";

@Component({
  selector: 'share-in-zenodo',
  templateUrl: './shareInZenodo.component.html'
})
export class ShareInZenodoComponent {
  public url: string = null;
  public title: string = "Share in Zenodo";
  properties: EnvProperties = properties;
  communityId: string = null;
  private community: CommunityInfo = null;
  public pageContents = null;
  public divContents = null;
  
  
  // public warningMessage = "";
  // public infoMessage = "";
  
  masterZenodoCommunityId = null;
  masterZenodoCommunity = null;
  
  communityIds = null;
  communities = [];
  page = 1;
  size = 5;
  zenodoCommunitiesLoadedCount = 0;
  zenodoSearchUtils: SearchUtilsClass = new SearchUtilsClass();
  errorCodes: ErrorCodes = new ErrorCodes();
  depositLink = "https://zenodo.org/deposit/new?c=";
  depositLearnHowPage: string = null;
  public routerHelper: RouterHelper = new RouterHelper();
  breadcrumbs: Breadcrumb[] = [];
  
  subs: Subscription[] = [];
  
  constructor(private  route: ActivatedRoute,
              private _router: Router,
              private _meta: Meta,
              private _title: Title,
              private _zenodoCommunitieService: ZenodoCommunitiesService,
              private _communityService: CommunityService,
              private helper: HelperService,
              private _piwikService: PiwikService,
              private seoService: SEOService) {
  }
  
  public ngOnInit() {
    this.zenodoSearchUtils.status = this.errorCodes.LOADING;
    this.url = properties.domain + properties.baseLink + this._router.url;
    this.seoService.createLinkForCanonicalURL(this.url, false);
    this.updateUrl(this.url);
    this.updateTitle(this.title);
    this.updateDescription("Zenodo, repository, deposit, share");
    this.depositLearnHowPage = this.properties.depositLearnHowPage;
    this.breadcrumbs.push({name: 'home', route: '/'}, {
      name: "Deposit",
      route: this.depositLearnHowPage
    }, {name: "Deposit in zenodo", route: null});
    //this.getDivContents();
    this.getPageContents();
    this.subs.push(this._communityService.getCommunityAsObservable().subscribe(
      community => {
        if (community) {
          this.communityId = community.communityId;
          this.subs.push(this._piwikService.trackView(this.properties, this.title).subscribe());
          this.community = community;
          this.masterZenodoCommunityId = this.community.zenodoCommunity;
          if (this.masterZenodoCommunityId) {
            this.subs.push(this._zenodoCommunitieService.getZenodoCommunityById(this.properties, this.properties.zenodoCommunities + this.masterZenodoCommunityId).subscribe(
              result => {
                this.masterZenodoCommunity = result;
                
              },
              error => {
                this.handleError("Error getting Master Zenodo community with id: " + this.masterZenodoCommunityId, error);
                
              }
            ));
          }
          this.zenodoSearchUtils.status = this.errorCodes.LOADING;
              this.communityIds = this.community.otherZenodoCommunities;
              this.zenodoSearchUtils.totalResults = this.communityIds.length;
              if (this.communityIds.length == 0) {
                this.zenodoSearchUtils.status = this.errorCodes.NONE;
              }
              this.getCommunities()
              

        }
      }));
    
  }
  
  public ngOnDestroy() {
    for (let sub of this.subs) {
      if (sub instanceof Subscriber) {
        sub.unsubscribe();
      }
    }
  }
  
  private updateDescription(description: string) {
    this._meta.updateTag({content: description}, "name='description'");
    this._meta.updateTag({content: description}, "property='og:description'");
  }
  
  private updateTitle(title: string) {
    var _title = ((title.length > 50) ? title.substring(0, 50) : title);
    this._title.setTitle(_title);
    this._meta.updateTag({content: _title}, "property='og:title'");
  }
  
  private updateUrl(url: string) {
    this._meta.updateTag({content: url}, "property='og:url'");
  }
  
  private getPageContents() {
    this.subs.push(this.helper.getPageHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
      this.pageContents = contents;
    }));
  }
  
  private getDivContents() {
    this.subs.push(this.helper.getDivHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
      this.divContents = contents;
    }));
  }
  
  getZenodoCommunityById(zenodoid) {
    this.subs.push(this._zenodoCommunitieService.getZenodoCommunityById(this.properties, this.properties.zenodoCommunities + zenodoid).subscribe(
      result => {
        this.communities[zenodoid] = result;
        this.zenodoCommunitiesLoadedCount++;
        if (this.zenodoCommunitiesLoadedCount >= this.communityIds.length || this.page * this.size) {
          this.zenodoSearchUtils.status = this.errorCodes.DONE;
        }
        
        
      },
      error => {
        // var emptyCommunity:ZenodoCommunityInfo = new ZenodoCommunityInfo();
        // emptyCommunity.id = zenodoid;
        // emptyCommunity.openaireId = openaireId;
        // emptyCommunity.title = zenodoid;
        // this.communities.push(emptyCommunity);
        this.zenodoCommunitiesLoadedCount++;
        if (this.zenodoCommunitiesLoadedCount >= this.communityIds.length) {
          this.zenodoSearchUtils.status = this.errorCodes.DONE;
        }
        //console.error("Zenodo community'"+zenodoid+"' couldn't be loaded");
        this.handleError("Error getting Zenodo community with id: " + zenodoid, error);
        
      }
    ));
  }
  
  private handleError(message: string, error) {
    console.error("Share in Zenodo Page: " + message, error);
  }
  
  public getCommunities($event = {value: 1}) {
    this.page = $event.value;
    for (let i = (this.page - 1) * this.size; i < this.communityIds.length && i < this.page * this.size; i++) {
      if (!this.communities[this.communityIds[i]["zenodoid"]]) {
        this.getZenodoCommunityById(this.communityIds[i]);
      }
    }
  }
  
}
