import {Component, Input, OnInit} from "@angular/core";
import {Stakeholder} from "../../openaireLibrary/monitor/entities/stakeholder";
import {StatisticsService} from "../../openaireLibrary/monitor-admin/utils/services/statistics.service";
import {IndicatorStakeholderBaseComponent} from "../../openaireLibrary/monitor-admin/utils/stakeholder-base.component";
import {zip} from "rxjs";
import {OAIndicator} from "../../openaireLibrary/monitor-admin/utils/indicator-utils";

@Component({
  selector: "oa-indicator",
  template: `
      <ng-container *ngIf="percentage > 0">
          <div class="uk-progress-semicircle open-access" [attr.percentage]="percentage"
               [style]="'--percentage:' + percentage"></div>
          <div class="uk-flex uk-flex-middle uk-margin-small-top">
              <icon class="open-access" [name]="'open_access'" [flex]="true"></icon>
              <span class="uk-margin-xsmall-left">Open Access</span>
          </div>
      </ng-container>
  `
})
export class OaIndicatorComponent extends IndicatorStakeholderBaseComponent implements OnInit {
  @Input()
  public stakeholder: Stakeholder;
  public percentage: number = 0;

  constructor(private statisticsService: StatisticsService) {
    super();
  }

  ngOnInit(): void {
    this.initPercentage();
  }

  public initPercentage(): void {
    let OAIndicator: OAIndicator = this.stakeholderUtils.openAccess.get(this.stakeholder.type);
    if(OAIndicator) {
      this.subscriptions.push(zip(
          this.statisticsService.getNumbers(this.indicatorUtils.getSourceType(OAIndicator.numerator.source), this.indicatorUtils.getFullUrl(this.stakeholder, OAIndicator.numerator)),
          this.statisticsService.getNumbers(this.indicatorUtils.getSourceType(OAIndicator.denominator.source), this.indicatorUtils.getFullUrl(this.stakeholder, OAIndicator.denominator))).subscribe(res => {
        let numerator = this.calculate(res[0], OAIndicator.numerator.jsonPath);
        let denominator = this.calculate(res[1], OAIndicator.denominator.jsonPath);
        if (denominator > 0) {
          this.percentage = Math.round(numerator * 100 / denominator);
        }
      }));
    }
  }

  public calculate(response: any, jsonPath: string[]) {
    let result = JSON.parse(JSON.stringify(response));
    jsonPath.forEach(path => {
      if (result) {
        result = result[path];
      }
    });
    if (typeof result === 'string' || typeof result === 'number') {
      result = Number(result);
      if (result === Number.NaN) {
        result = 0;
      }
    } else {
      result = 0;
    }
    return result;
  }
}
