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";

@Component({
	selector: 'sdg',
	templateUrl: 'sdg.component.html',
	styleUrls: ['sdg.component.css']
})
export class SdgComponent implements OnInit, OnDestroy {
	
	private sdgs: any = [];
	private sdgsResearchOutcomes: any = [];
	public displayedSdgs: any = [];

	public loading: boolean;
	properties: EnvProperties = properties;
	public breadcrumbs: Breadcrumb[] = [{name: 'home', route: '/'}, {name: 'SDG'}];

	subscriptions: Subscription[] = [];

	constructor(
		private httpClient: HttpClient, private refineFieldResultsService: RefineFieldResultsService
	) {}

	ngOnInit() {
		this.loading = true;
		this.httpClient.get('/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();
    }
  }
}