import {Component} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Meta, Title} from '@angular/platform-browser';
import {PiwikService} from '../openaireLibrary/utils/piwik/piwik.service';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
import {HelperService} from "../openaireLibrary/utils/helper/helper.service";
import {SEOService} from "../openaireLibrary/sharedComponents/SEO/SEO.service";
import {properties} from "../../environments/environment";
import {Subscriber} from "rxjs";
import {Breadcrumb} from '../openaireLibrary/utils/breadcrumbs/breadcrumbs.component';

@Component({
  selector: 'support',
  templateUrl: 'support.component.html',
  styleUrls: ['support.component.less']
})
export class SupportComponent {
  public pageContents = null;
  public divContents = null;
  
  public url: string = null;
  public pageTitle: string = "OpenAIRE - Monitor | Support";
  public description: string = "OpenAIRE - Monitor | Support";
	public breadcrumbs: Breadcrumb[] = [{name: 'home', route: '/'}, {name: 'Support'}];
  public properties: EnvProperties = properties;
  subscriptions = [];

  constructor(
    private route: ActivatedRoute,
    private _router: Router,
    private _meta: Meta,
    private _title: Title,
    private seoService: SEOService,
    private _piwikService: PiwikService,
    private helper: HelperService) {
  }
  
  public ngOnInit() {
    this.subscriptions.push(this._piwikService.trackView(this.properties, this.pageTitle).subscribe());
    this.url = this.properties.domain + this.properties.baseLink + this._router.url;
    this.seoService.createLinkForCanonicalURL(this.url);
    this.updateUrl(this.url);
    this.updateTitle(this.pageTitle);
    this.updateDescription(this.description);
    //this.getDivContents();
    this.getPageContents();
  }
  
  private getPageContents() {
    this.subscriptions.push(this.helper.getPageHelpContents(this.properties, 'monitor', this._router.url).subscribe(contents => {
      this.pageContents = contents;
    }));
  }
  
  private getDivContents() {
    this.subscriptions.push(this.helper.getDivHelpContents(this.properties, 'monitor', this._router.url).subscribe(contents => {
      this.divContents = contents;
    }));
  }

  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.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'");
  }
}
