import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {CountryUsageStat, UsageStat} from '../entities/usage-stat';
import {FormControl} from '@angular/forms';
import {Observable, Subscriber, Subscription} from 'rxjs';
import {UsageStatsService} from '../services/usage-stats.service';
import {map, startWith} from 'rxjs/operators';
import {countries} from '../services/countries';
import {DomSanitizer, Meta, SafeUrl, Title} from '@angular/platform-browser';
import {StringUtils} from '../openaireLibrary/utils/string-utils.class';
import {ActivatedRoute, Router} from '@angular/router';
import {NumberUtils} from '../openaireLibrary/utils/number-utils.class';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
import {properties} from '../../environments/environment';
import {PiwikService} from '../openaireLibrary/utils/piwik/piwik.service';
import {SEOService} from '../openaireLibrary/sharedComponents/SEO/SEO.service';
import {SearchInputComponent} from '../openaireLibrary/sharedComponents/search-input/search-input.component';

@Component({
  selector: 'analytics',
  templateUrl: 'analytics.component.html',
  styleUrls: ['analytics.component.css'],
})
export class AnalyticsComponent implements OnInit, OnDestroy {
  public countryFb: FormControl;
  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[];
  properties: EnvProperties = properties;
  description = "Track Countries Usage Activity. Worldwide Monthly Usage Events, Monthly Views & Downloads.";
  title = "OpenAIRE - UsageCounts | Analytics";
  subs: Subscription[] = [];
  searchSub: Subscription = null;
  @ViewChild('searchInput') searchInput: SearchInputComponent;
  
  constructor(private usageStatsService: UsageStatsService,
              private route: ActivatedRoute,
              private router: Router,
              private _title: Title, private _piwikService: PiwikService,
              private _meta: Meta, private seoService: SEOService,
              private sanitizer: DomSanitizer) {
  }
  
  ngOnInit() {
    this._title.setTitle(this.title);
    this._meta.updateTag({content: this.description}, "name='description'");
    this._meta.updateTag({content: this.description}, "property='og:description'");
    this._meta.updateTag({content: this.title}, "property='og:title'");
    this._title.setTitle(this.title);
    let url = this.properties.domain + this.properties.baseLink + this.router.url;
    this.seoService.createLinkForCanonicalURL(url, false);
    this._meta.updateTag({content: url}, "property='og:url'");
    if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
      this.subs.push(this._piwikService.trackView(this.properties, this.title).subscribe());
    }
    this.init();
    this.search(true);
    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')
      ]
    }
  }
  
  public ngOnDestroy() {
    this.subs.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
    this.clearTimeouts();
  }
  
  private init() {
    this.countryFb = new FormControl(null);
    this.countries = this.countryFb.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(show: boolean = false) {
    this.country = this.countryFb.value;
    this.showSearch = show;
    this.loading = true;
    this.clearTimeouts();
    if (this.country && this.country.length > 0) {
      this.country = StringUtils.capitalize(this.country);
      this.searchSub = 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));
  }
  
  clearTimeouts() {
    this.timeouts.forEach(timeout => {
      clearTimeout(timeout);
    });
    this.state = 0;
    if(this.searchSub instanceof Subscription) {
      this.searchSub.unsubscribe();
    }
  }
  
  reset() {
    this.clearTimeouts();
    if (this.state == 0) {
      this.init();
      this.searchInput.reset();
      this.search(true);
    }
  }
  
  public getSafeUrl(url: string): SafeUrl {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}
