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 {DomSanitizer, SafeUrl, Title} from '@angular/platform-browser';
import {StringUtils} from '../openaireLibrary/utils/string-utils.class';
import {ActivatedRoute} from '@angular/router';
import {NumberUtils} from '../openaireLibrary/utils/number-utils.class';

@Component({
  selector: 'analytics',
  templateUrl: 'analytics.component.html',
  styleUrls: ['analytics.component.css'],
})
export class AnalyticsComponent implements OnInit {
  public countryFb: FormGroup;
  public countries: Observable<string[]>;
  public country: string;
  public loading: boolean = true;
  public iframeLoading: boolean = true;
  public display: UsageStat | CountryUsageStat;
  public showSearch: boolean = false;
  public state: number = 0;
  private timeouts: any[] = [];
  public years = 0;
  public charts: SafeUrl[];
  @ViewChild('input') input: ElementRef;
  
  constructor(private usageStatsService: UsageStatsService,
              private route: ActivatedRoute,
              private title: Title,
              private sanitizer: DomSanitizer) {
  }
  
  ngOnInit() {
    this.title.setTitle('OpenAIRE - UsageCounts | Analytics');
    this.route.fragment.subscribe(fragment => {
      setTimeout(() => {
        this.goTo(fragment);
      }, 100);
    });
    this.init();
    this.search();
    for(let i = 0; i < 3; i++) {
      this.charts = [
        this.getSafeUrl('https://docs.google.com/spreadsheets/d/e/2PACX-1vQ-HejU11H1dMKa2MeIvLevnH0jtJUvduan3WMTjgDYCeq6g_WBPFBbZvg83hLuMv7XNyDQ3vHZWNYc/pubchart?oid=919355937&amp;format=interactive'),
        this.getSafeUrl('https://docs.google.com/spreadsheets/d/e/2PACX-1vQ-HejU11H1dMKa2MeIvLevnH0jtJUvduan3WMTjgDYCeq6g_WBPFBbZvg83hLuMv7XNyDQ3vHZWNYc/pubchart?oid=1667183135&amp;format=interactive'),
        this.getSafeUrl('https://docs.google.com/spreadsheets/d/e/2PACX-1vQ-HejU11H1dMKa2MeIvLevnH0jtJUvduan3WMTjgDYCeq6g_WBPFBbZvg83hLuMv7XNyDQ3vHZWNYc/pubchart?oid=2070534117&amp;format=interactive')
      ]
    }
  }
  
  private init() {
    this.countryFb = new FormGroup({
      country: new FormControl(null)
    });
    this.countries = this.countryFb.get('country').valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      );
  }
  
  changeYear(i: number) {
    if(!this.iframeLoading) {
      this.iframeLoading = true;
      this.years = i;
    }
  }
  
  onLoad() {
    this.iframeLoading = false;
  }
  
  roundUsageStat(stats: UsageStat) {
    if(stats) {
      stats.repositories = NumberUtils.roundNumber(Number.parseInt(stats.repositories));
      stats.total_downloads = NumberUtils.roundNumber(Number.parseInt(stats.total_downloads));
      stats.total_views = NumberUtils.roundNumber(Number.parseInt(stats.total_views));
    }
    return stats;
  }
  
  roundCountryUsageStat(stats: CountryUsageStat) {
    if(stats) {
      stats.total_repos = NumberUtils.roundNumber(Number.parseInt(stats.total_repos));
      stats.downloads = NumberUtils.roundNumber(Number.parseInt(stats.downloads));
      stats.views = NumberUtils.roundNumber(Number.parseInt(stats.views));
    }
    return stats;
  }
  
  public search() {
    this.country = this.countryFb.value.country;
    this.showSearch = false;
    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 = this.roundCountryUsageStat(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 = this.roundUsageStat(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);
    }
  }
  
  closeSearch() {
    this.showSearch = false;
  }
  
  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();
    }
  }
  
  goTo(id: string) {
    const yOffset = -100;
    const element = document.getElementById(id);
    if(element) {
      const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;
      window.scrollTo({top: y, behavior: 'smooth'});
    }
  }
  
  public getSafeUrl(url: string): SafeUrl {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}
