import {Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {CountryUsageStat, UsageStat} from '../entities/usage-stat'; import {FormControl, FormGroup} from '@angular/forms'; import {Observable} from 'rxjs'; import {UsageStatsService} from '../services/usage-stats.service'; import {map, startWith} from 'rxjs/operators'; import {countries} from '../services/countries'; import {Title} from '@angular/platform-browser'; import {StringUtils} from '../openaireLibrary/utils/string-utils.class'; @Component({ selector: 'analytics', templateUrl: 'analytics.component.html', styleUrls: ['analytics.component.css'], }) export class AnalyticsComponent implements OnInit { public countryFb: FormGroup; public countries: Observable; public country: string; public loading: boolean = true; public display: UsageStat | CountryUsageStat; public showSearch: boolean = false; public state: number = 0; private timeouts: any[] = []; @ViewChild('input') input: ElementRef; constructor(private usageStatsService: UsageStatsService, private title: Title) { } ngOnInit() { this.title.setTitle('OpenAIRE - UsageCounts | Analytics'); this.init(); this.search(); } private init() { this.countryFb = new FormGroup({ country: new FormControl(null) }); this.countries = this.countryFb.get('country').valueChanges .pipe( startWith(''), map(value => this._filter(value)) ); } public search() { this.country = this.countryFb.value.country; this.loading = true; this.clearTimeouts(); if (this.country && this.country.length > 0) { this.country = StringUtils.capitalize(this.country); this.usageStatsService.getCountryMetrics(this.country).subscribe(stats => { this.display = stats; this.loading = false; if(this.display) { this.state = 1; this.animation(); } }, error => { this.display = null; this.loading = false; }); } else { this.usageStatsService.getAllMetrics().subscribe(stats => { this.display = stats; this.loading = false; if(this.display) { this.state = 1; this.animation(); } }, error => { this.display = null; this.loading = false; }); } } private animation() { this.timeouts.push(setTimeout(() => { if(this.state != 3) { this.animation(); } this.state++; }, 800)); } private _filter(value: string): string[] { const filterValue = value.toLowerCase(); return countries.map(value => value.name).filter(option => filterValue && option.toLowerCase().includes(filterValue)); } toggle() { this.showSearch = !this.showSearch; if (this.showSearch) { setTimeout(() => { // this will make the execution after the above boolean has changed this.input.nativeElement.focus(); }, 0); } } clearTimeouts() { this.timeouts.forEach(timeout => { clearTimeout(timeout); }); this.state = 0; } reset() { this.clearTimeouts(); if(this.state == 0) { this.init(); this.showSearch = true; setTimeout(() => { // this will make the execution after the above boolean has changed this.input.nativeElement.focus(); }, 0); this.search(); } } }