import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {SearchResearchResultsService} from '../../services/searchResearchResults.service';
import {SearchDataprovidersService} from '../../services/searchDataproviders.service';
import {RefineFieldResultsService} from '../../services/refineFieldResults.service';
import {EnvProperties} from '../../utils/properties/env-properties';
import {properties} from '../../../../environments/environment';
import {NumberSize, NumberUtils} from '../../utils/number-utils.class';
import {BehaviorSubject, Observable, Subscription, zip} from 'rxjs';
import {RouterHelper} from "../../utils/routerHelper.class";
import {OpenaireEntities} from "../../utils/properties/searchFields";
import {SearchOrganizationsService} from '../../services/searchOrganizations.service';
import {GroupedRequestsService} from "../../services/groupedRequests.service";

export interface Numbers {
  publicationsSize?: NumberSize;
  datasetsSize?: NumberSize;
  datasetsLinkedSize?: NumberSize;
  softwareLinkedSize?: NumberSize;
  softwareSize?: NumberSize;
  otherSize?: NumberSize;
  fundersSize?: NumberSize;
  mergedFundersSize?: NumberSize;
  projectsSize?: NumberSize;
  datasourcesSize?: NumberSize;
	organizationsSize?: NumberSize;
}

@Component({
  selector: 'numbers',
  template: `
		<div *ngIf="showContentWithNumbers" class="uk-margin-top" style="max-width: 600px;" uk-scrollspy-class>
			<div>
				A comprehensive and open dataset of research information covering 
				<span *ngIf="hasPublications" class="uk-text-bold">{{numbers.publicationsSize.number|number}}<span class="uk-text-lowercase">{{numbers.publicationsSize.size}}</span> {{openaireEntities.PUBLICATIONS.toLowerCase()}}</span>
				<ng-container *ngIf="(hasPublications && (hasDatasets || hasSoftware || (hasDatasources || hasProjects || hasOrganizations)))">, </ng-container>
				<span *ngIf="hasDatasets" class="uk-text-bold">{{numbers.datasetsSize.number|number}}<span class="uk-text-lowercase">{{numbers.datasetsSize.size}}</span> {{openaireEntities.DATASETS.toLowerCase()}}</span>
				<ng-container *ngIf="(hasDatasets && (hasSoftware || (hasDatasources || hasProjects || hasOrganizations)))">, </ng-container>
				<span *ngIf="hasSoftware" class="uk-text-bold">{{numbers.softwareSize.number|number}}<span class="uk-text-lowercase">{{numbers.softwareSize.size}}</span> {{openaireEntities.SOFTWARE.toLowerCase()}} items</span>
				<ng-container *ngIf="(hasSoftware && (hasDatasources || hasProjects || hasOrganizations))">, </ng-container>
				<ng-container *ngIf="((hasPublications || hasDatasets || hasSoftware) && (hasDatasources))"> from </ng-container>
				<span *ngIf="hasDatasources" class="uk-text-bold">{{numbers.datasourcesSize.number|number}}<span class="uk-text-lowercase">{{numbers.datasourcesSize.size}}</span> {{openaireEntities.DATASOURCES.toLowerCase()}}</span>
				<ng-container *ngIf="(hasDatasources) && ((hasProjects) || hasOrganizations)">, linked to </ng-container>
				<span *ngIf="hasProjects" class="uk-text-bold">{{numbers.projectsSize.number|number}}<span class="uk-text-lowercase">{{numbers.projectsSize.size}}</span> grants</span>
				<ng-container *ngIf="hasProjects && hasOrganizations"> and </ng-container>
				<span *ngIf="hasOrganizations" class="uk-text-bold">{{numbers.organizationsSize.number|number}}<span class="uk-text-lowercase">{{numbers.organizationsSize.size}}</span> {{openaireEntities.ORGANIZATIONS.toLowerCase()}}</span>.
			</div>
			<div class="uk-text-primary">All linked together through citations and semantics.</div>
		</div>
  `,
})
export class NumbersComponent implements OnInit, OnDestroy {
  /** Add a value if you want to apply refine query*/
  @Input() refineValue = null;
  /** True: Default initialization
   *  False: Call init method to initialize numbers */
  @Input() defaultInit = true;
  /** When numbers have been initialized this emitter will emitted */
	@Output() results: EventEmitter<Numbers> = new EventEmitter<Numbers>();
	
	showPublications: boolean = true;
  showDatasets: boolean = true;
  showSoftware: boolean = true;
  showOrp: boolean = true;
  showOrganizations: boolean = true;
  showProjects: boolean = true;
  showDataProviders: boolean = true;
	numbersLimit: number = 100;
  public properties: EnvProperties = properties;
  public openaireEntities = OpenaireEntities;
  public routerHelper: RouterHelper = new RouterHelper();
  public numbers: Numbers = {};
  private emptySubject: BehaviorSubject<number> = new BehaviorSubject<number>(0);
  private subs: any[] = [];
  
  constructor(private searchResearchResultsService: SearchResearchResultsService,
              private searchDataprovidersService: SearchDataprovidersService,
              private refineFieldResultsService: RefineFieldResultsService,
							private _searchOrganizationsService: SearchOrganizationsService,
              private groupedRequestsService: GroupedRequestsService) {
    this.emptySubject = new BehaviorSubject<number>(0);
  }
  
  ngOnInit() {
    if (this.defaultInit) {
      this.init();
    }
  }
  
  init(getDatasetsLinked = false, getSoftwareLinked = false, getPublications = true, getDatasets = true,
      getSoftware = true, getOther = true, getProjects = true, getDataProviders = true, getOrganizations = true, refineValue: string = null) {
    if (refineValue) {
      this.refineValue = refineValue;
    }
    let refineParams = (this.refineValue) ? ('&fq=' + this.refineValue) : null;

    if (refineParams) {
      let mergedFundersSet = new Set<string>();
      this.subs.push(zip(
        (getPublications) ? this.searchResearchResultsService.numOfSearchResults('publication', '', this.properties, refineParams) : this.empty,
        (getDatasets) ? this.searchResearchResultsService.numOfSearchResults('dataset', '', this.properties, refineParams) : this.empty,
        (getDatasetsLinked) ? this.searchResearchResultsService.numOfSearchResultsLinkedToPub("dataset", this.properties) : this.empty,
        (getSoftware) ? this.searchResearchResultsService.numOfSearchResults('software', '', this.properties, refineParams) : this.empty,
        (getSoftwareLinked) ? this.searchResearchResultsService.numOfSearchResultsLinkedToPub("software", this.properties) : this.empty,
        (getOther) ? this.searchResearchResultsService.numOfSearchResults('other', '', this.properties, refineParams) : this.empty,
        (getProjects) ? this.refineFieldResultsService.getAllRefineFieldResultsByFieldName('funder', 'project', this.properties, refineParams) : this.empty,
        (getDataProviders) ? this.searchDataprovidersService.numOfSearchDataproviders('', this.properties, refineParams) : this.empty,
        (getOrganizations) ? this._searchOrganizationsService.numOfSearchOrganizations2('', this.properties, refineParams) : this.empty,
        (getPublications && getDatasets && getSoftware && getOther) ? this.refineFieldResultsService.getAllRefineFieldResultsByFieldName('relfunder', 'result', this.properties, refineParams) : this.empty,
      ).subscribe((data: any[]) => {
          if (data[0] && data[0] > 0) {
            this.numbers.publicationsSize = NumberUtils.roundNumber(data[0]);
          }
          if (data[1] && data[1] > 0) {
            this.numbers.datasetsSize = NumberUtils.roundNumber(data[1]);
          }
          if (data[2] && data[2] > 0) {
            this.numbers.datasetsLinkedSize = NumberUtils.roundNumber(data[2]);
          }
          if (data[3] && data[3] > 0) {
            this.numbers.softwareSize = NumberUtils.roundNumber(data[3]);
          }
          if (data[4] && data[4] > 0) {
            this.numbers.softwareLinkedSize = NumberUtils.roundNumber(data[4]);
          }
          if (data[5] && data[5] > 0) {
            this.numbers.otherSize = NumberUtils.roundNumber(data[5]);
          }
          if (data[6][0] && data[6][0] > 0) {
            this.numbers.projectsSize = NumberUtils.roundNumber(data[6][0]);
          }
          if (data[6][1] && data[6][1].length > 0 && data[6][1][0].filterId == 'funder' && data[6][1][0].values) {
            this.numbers.fundersSize = NumberUtils.roundNumber(data[6][1][0].values.length);

            let queriedFunders = data[6][1][0].values;
            queriedFunders.forEach(queriedFunder => {
              if (+queriedFunder.number > 1) {
                if (!mergedFundersSet.has(queriedFunder.id)) {
                  mergedFundersSet.add(queriedFunder.id);
                }
              }
            });
          }
          if (data[7] && data[7] > 0) {
            this.numbers.datasourcesSize = NumberUtils.roundNumber(data[7]);
          }
          if (data[8] && data[8] > 0) {
            this.numbers.organizationsSize = NumberUtils.roundNumber(data[8]);
          }
          if (data[9][1] && data[9][1].length > 0 && data[9][1][0].filterId == 'relfunder' && data[9][1][0].values) {
            let queriedFunders = data[9][1][0].values;
            queriedFunders.forEach(queriedFunder => {
              if (!mergedFundersSet.has(queriedFunder.id)) {
                mergedFundersSet.add(queriedFunder.id);
              }
            });
          }

          this.numbers.mergedFundersSize = NumberUtils.roundNumber(mergedFundersSet.size);
        }
      ), err => {
        this.handleError('Error getting numbers', err);
      });
    } else {
      this.subs.push(this.groupedRequestsService.home().subscribe((data: any[]) => {
        if (data) {
          if (data.hasOwnProperty("publications") && data['publications'] > 0) {
            this.numbers.publicationsSize = NumberUtils.roundNumber(data['publications']);
          }
          if (data.hasOwnProperty("datasets") && data['datasets'] > 0) {
            this.numbers.datasetsSize = NumberUtils.roundNumber(data['datasets']);
          }
          if (data.hasOwnProperty("datasetsInterlinked") && data['datasetsInterlinked'] > 0) {
            this.numbers.datasetsLinkedSize = NumberUtils.roundNumber(data['datasetsInterlinked']);
          }
          if (data.hasOwnProperty("software") && data['software'] > 0) {
            this.numbers.softwareSize = NumberUtils.roundNumber(data['software']);
          }
          if (data.hasOwnProperty("softwareInterlinked") && data['softwareInterlinked'] > 0) {
            this.numbers.softwareLinkedSize = NumberUtils.roundNumber(data['softwareInterlinked']);
          }
          if (data.hasOwnProperty("other") && data['other'] > 0) {
            this.numbers.otherSize = NumberUtils.roundNumber(data['other']);
          }
          if (data.hasOwnProperty("projects") && data['projects'] > 0) {
            this.numbers.projectsSize = NumberUtils.roundNumber(data['projects']);
          }
          if (data.hasOwnProperty("funders") && data['funders'] > 0) {
            this.numbers.mergedFundersSize = NumberUtils.roundNumber(data['funders']);
          }
          if (data.hasOwnProperty("datasources") && data['datasources'] > 0) {
            this.numbers.datasourcesSize = NumberUtils.roundNumber(data['datasources']);
          }
          if (data.hasOwnProperty("organizations") && data['organizations'] > 0) {
            this.numbers.organizationsSize = NumberUtils.roundNumber(data['organizations']);
          }
        }
        this.results.emit(this.numbers);
      }, err => {
        this.handleError('Error getting numbers', err);
      }));
    }
  }
  
  ngOnDestroy() {
    this.subs.forEach(sub => {
      if (sub instanceof Subscription) {
        sub.unsubscribe();
      }
    });
  }
  
  get empty(): Observable<number> {
    return this.emptySubject.asObservable();
  }
  
  private handleError(message: string, error) {
    console.error('Numbers: ' + message, error);
  }

	public get showContentWithNumbers() {
    if (this.numbers && (this.hasPublications || this.hasDatasets || this.hasSoftware || this.hasDatasources || this.hasProjects || this.hasOrganizations)) {
      return true;
    }
  }

	public get hasPublications() {
    return this.showPublications && this.numbers.publicationsSize && this.numbers.publicationsSize.count >= this.numbersLimit;
  }

  public get hasDatasets() {
    return this.showDatasets && this.numbers.datasetsSize && this.numbers.datasetsSize.count >= this.numbersLimit;
  }

  public get hasSoftware() {
    return this.showSoftware && this.numbers.softwareSize && this.numbers.softwareSize.count >= this.numbersLimit;
  }

  public get hasDatasources() {
    return this.showDataProviders && this.numbers.datasourcesSize && this.numbers.datasourcesSize.count >= this.numbersLimit;
  }

  public get hasProjects() {
    return this.showProjects && this.numbers.projectsSize && this.numbers.projectsSize.count >= this.numbersLimit;
  }

  public get hasOrganizations() {
    return this.showOrganizations && this.numbers.organizationsSize && this.numbers.organizationsSize.count >= this.numbersLimit;
  }
}
