import {HttpClient} from "@angular/common/http";
import {Component, OnDestroy, OnInit} from "@angular/core";
import {Subscription} from "rxjs";

import {Breadcrumb} from "../openaireLibrary/utils/breadcrumbs/breadcrumbs.component";
import {EnvProperties} from "../openaireLibrary/utils/properties/env-properties";
import {properties} from "src/environments/environment";
import {RefineFieldResultsService} from "../openaireLibrary/services/refineFieldResults.service";
import {OpenaireEntities} from "../openaireLibrary/utils/properties/searchFields";
import {StringUtils} from "../openaireLibrary/utils/string-utils.class";
import {Router} from '@angular/router';
import {Meta, Title} from "@angular/platform-browser";
import {SEOService} from "../openaireLibrary/sharedComponents/SEO/SEO.service";
import {PiwikService} from "../openaireLibrary/utils/piwik/piwik.service";

@Component({
	selector: 'sdg',
	templateUrl: 'sdg.component.html',
	styleUrls: ['sdg.component.less']
})
export class SdgComponent implements OnInit, OnDestroy {
	public url: string = null;
	public pageTitle: string = "OpenAIRE | Sustainable Development Goals";
	public pageDescription: string = "Laying the foundation for new approaches and solutions. We have developed a classification scheme for UN Sustainable Development Goals, to view contributions of research towards complex challenges for humanity such as climate change, biodiversity loss, pollution and poverty reduction.";
	
	private sdgs: any = [];
	private sdgsResearchOutcomes: any = [];
	public displayedSdgs: any = [];

	public loading: boolean;
	properties: EnvProperties = properties;
  openaireEntities = OpenaireEntities;
	public breadcrumbs: Breadcrumb[] = [{name: 'home', route: '/'}, {name: 'Sustainable Development Goals'}];

	subscriptions: Subscription[] = [];

	constructor(
		private httpClient: HttpClient, private refineFieldResultsService: RefineFieldResultsService,
		private _router: Router,
		private _meta: Meta,
		private _title: Title,
		private seoService: SEOService,
		private _piwikService: PiwikService
	) {}

	ngOnInit() {
		this.loading = true;
		if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
      this.subscriptions.push(this._piwikService.trackView(this.properties, this.pageTitle, this.properties.piwikSiteId).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.pageDescription);
		this.httpClient.get(properties.domain+'/assets/vocabulary/sdg.json').subscribe(data => {
			this.sdgs = data['sdg'];
		});
		this.refineFieldResultsService.getRefineFieldsResultsByEntityName(['sdg'], 'result', this.properties, null).subscribe(data => {
			this.sdgsResearchOutcomes = data[1][0].values;
			let merged =[];
			for(let i=0; i<this.sdgs.length; i++){
				merged.push({
					...this.sdgs[i],
					...(this.sdgsResearchOutcomes.find((innerItem) => innerItem.id === this.sdgs[i].id))
				});
			}
			this.displayedSdgs = merged;
			this.loading = false;
		});
	}

	public ngOnDestroy() {
    for (let sub of this.subscriptions) {
      sub.unsubscribe();
    }
  }

  public urlEncodeAndQuote(str: string): string {
    return StringUtils.quote(StringUtils.URIEncode(str));
  }

	private updateUrl(url: string) {
    this._meta.updateTag({content: url}, "property='og:url'");
  }

	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 updateDescription(description: string) {
    this._meta.updateTag({content: description}, "name='description'");
    this._meta.updateTag({content: description}, "property='og:description'");
  }
}
