import {Component, HostListener, OnDestroy, OnInit} from '@angular/core';
import {Meta, Title} from '@angular/platform-browser';
import {ActivatedRoute, Router} from '@angular/router';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
import {properties} from '../../environments/environment';
import {Subscriber, Subscription} from 'rxjs';
import {PiwikService} from '../openaireLibrary/utils/piwik/piwik.service';
import {SEOService} from '../openaireLibrary/sharedComponents/SEO/SEO.service';

@Component({
  selector: 'resources',
  templateUrl: 'resources.component.html',
  styleUrls: ['resources.component.css'],
})
export class ResourcesComponent implements OnInit, OnDestroy {
  properties: EnvProperties = properties;
  description = "OpenAIRE Provide. The resources of the OpenAIRE UsageCounts Service are available through the OpenAIRE PROVIDE product, which is serving the content providers. APIs and Reports.";
  title = "OpenAIRE - UsageCounts | Resources";
  subs: Subscription[] = [];
  large: boolean = false;
  
  constructor(private router: Router,
              private _title: Title, private _piwikService: PiwikService,
              private _meta: Meta, private seoService: SEOService,
              private route: ActivatedRoute) {
  }
  
  @HostListener('window:resize', ['$event'])
  onResize(event) {
    if(event.target.innerWidth > 959 && this.large === false) {
      this.large = true;
    } else if(event.target.innerWidth < 960 && this.large === true){
      this.large = false;
    }
  }
  
  ngOnInit() {
    if(typeof window !== 'undefined') {
      this.large = window.innerWidth > 959;
    }
    this._title.setTitle(this.title);
    this._meta.updateTag({content: this.description}, "name='description'");
    this._meta.updateTag({content: this.description}, "property='og:description'");
    this._meta.updateTag({content: this.title}, "property='og:title'");
    this._title.setTitle(this.title);
    let url = this.properties.domain + this.properties.baseLink + this.router.url;
    this.seoService.createLinkForCanonicalURL(url, false);
    this._meta.updateTag({content: url}, "property='og:url'");
    if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
      this.subs.push(this._piwikService.trackView(this.properties, this.title).subscribe());
    }
  }
  
  public ngOnDestroy() {
    this.subs.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }
}
