import {Component, OnInit} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import {SEOService} from "../openaireLibrary/sharedComponents/SEO/SEO.service";
import {PiwikService} from "../openaireLibrary/utils/piwik/piwik.service";
import {Meta, Title} from "@angular/platform-browser";
import {SearchOrcidService} from "../openaireLibrary/claims/claim-utils/service/searchOrcid.service";

import {CustomFilterService} from "../openaireLibrary/shared/customFilter.service";
import {SearchResearchResultsService} from "../openaireLibrary/services/searchResearchResults.service";
import {LayoutService} from "../openaireLibrary/dashboard/sharedComponents/sidebar/layout.service";
import {ResearcherBaseComponent} from "../shared/researcher-base.component";
import {LinksResolver} from "../search/links-resolver";
import {SearchCustomFilter} from "../openaireLibrary/searchPages/searchUtils/searchUtils.class";
import {properties} from "../../environments/environment";
import {StakeholderService} from "../openaireLibrary/monitor/services/stakeholder.service";
import {ConfigurationService} from "../openaireLibrary/utils/configuration/configuration.service";
import {OpenaireEntities} from "../openaireLibrary/utils/properties/searchFields";

@Component({
  selector: 'researcher',
  template: `
    <loading *ngIf="loading" class="uk-position-center"></loading>
    <div *ngIf="!loading">
      <div class="uk-banner uk-light">
        <div class="uk-container uk-container-large">
          <div class="uk-padding-small uk-padding-remove-vertical">
            <div *ngIf="authorId && author" class="uk-grid uk-grid-large uk-flex-middle" uk-grid>
              <div class="uk-width-expand">
                <div class="uk-grid uk-grid-small uk-flex-middle" uk-grid>
                  <div>
                    <div class="uk-card uk-card-primary uk-border-circle uk-padding-small">
                      <icon [name]="'person'" [ratio]="4.5" [flex]="true"></icon>
                    </div>
                  </div>
                  <div class="uk-width-expand uk-margin-small-left">
                    <div class="uk-h4 uk-margin-xsmall-bottom uk-text-truncate">{{author.authorGivenName}} {{author.authorFamilyName}}</div>
                    <div class="uk-text-xsmall uk-text-bold uk-margin-bottom">
                      <div *ngIf="totalResults > 0">{{totalResults}} {{openaireEntities.RESULTS}}</div>
                      <div *ngIf="author.institutions" class="uk-text-truncate">{{author.institutions.join(", ")}} </div>
                    </div>
                    <div class="uk-flex uk-flex-middle uk-text-small uk-text-italic">
                      <img src="assets/common-assets/common/ORCIDiD_icon16x16.png" alt="orcid"
                            loading="lazy" style="width:16px; height:16px;" class="uk-margin-xsmall-right">
                      <a [href]="properties.orcidURL + author.id" target="_blank">
                        {{properties.orcidURL + author.id}}
                      </a>
                    </div>
                  </div>
                  <div *ngIf="openResults && totalResults" class="uk-width-auto">
                    <div class="uk-progress-semicircle open-access" [attr.percentage]="getPercentage()" [style]="'--percentage:' + getPercentage()"></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>
                  </div>
                </div>
              </div>
            </div>
            <h1 *ngIf="!authorId" class="uk-h3 uk-margin-small-bottom">Researcher Monitors</h1>
          </div>
        </div>
        <div *ngIf="stakeholder" class="uk-banner-footer">
          <div class="uk-container uk-container-large uk-flex uk-flex-between">
            <ul class="uk-banner-tab uk-padding-small uk-padding-remove-vertical">
              <li [class.uk-active]="!isSearch">
                <a [routerLink]="['./', stakeholder.alias]" [relativeTo]="_route" (click)="isSearch = false">
                  {{entities.stakeholder}}
                </a>
              </li>
              <li [class.uk-active]="isSearch">
                <a [routerLink]="['./', stakeholder.alias, 'search']" [queryParams]="routerHelper.createQueryParams(['type','peerreviewed'], [quote('publications'), quote('true')])" [relativeTo]="_route">
                  Browse {{openaireEntities.RESULTS}}
                </a>
              </li>
            </ul>

          </div>
        </div>
      </div>
      <div class="uk-container uk-container-large uk-margin-medium-top uk-margin-medium-bottom">
        <router-outlet></router-outlet>
      </div>
    </div>
  `
})
export class ResearcherComponent extends ResearcherBaseComponent  implements OnInit {
  totalResults: number;
  openResults: number;
  loading: boolean = false;
  stakeholder;
  isSearch: boolean = false;
  openaireEntities = OpenaireEntities;

  constructor(protected _router: Router,
              protected _route: ActivatedRoute,
              protected seoService: SEOService,
              protected _piwikService: PiwikService,
              protected _title: Title,
              protected _meta: Meta,
              protected _searchOrcidService: SearchOrcidService,
              protected _searchResearchResultsService: SearchResearchResultsService,
              private _customFilterService: CustomFilterService,
              private layoutService: LayoutService,
              private stakeholderService: StakeholderService,
              private configurationService: ConfigurationService) {
    super();
    super.initRouterParams(this._route, event => {
      this.isSearch = event.url.includes('/search');
    });
  }


  ngOnInit() {
    this.layoutService.setRootClass('researcher');
    this.params.subscribe(params => {
      this.authorId = params['stakeholder'];
      if (this.authorId) {
        if(this.stakeholder?.index_id !== this.authorId) {
          this.loading = true;
          this.author = null;
          this._customFilterService.setCustomFilter([]);

              this.orcid = {
                success: () => {
                  let name = this.author.authorGivenName + " " + (this.author.authorFamilyName?this.author.authorFamilyName:"");
                  this._customFilterService.setCustomFilter(
                    [/*new SearchCustomFilter("National", "country", "IE", "Irish National Monitor", false),*/
                      new SearchCustomFilter("Orcid", "authorId", this.authorId, name)
                    ]);
                  this.title = name;
                  this.description = name;
                  this.setProperties(this.orcid, "researcher", this.configurationService);
                  LinksResolver.resetProperties();
                  LinksResolver.setSearchAndResultLanding("researcher/" + this.authorId);
                  this.setMetadata();


                },
                error: () => {
                  this._router.navigate([properties.errorLink]);
                }
              }
              this.results = {
                success: (res: string | number) => {
                  this.totalResults = +res;
                  if(this.totalResults ==0 ){
                    this._router.navigate([properties.errorLink]);
                  }else{
                    this.loading = false;
                    this.subscriptions.push(this.stakeholderService.getResearcherStakeholder(this.authorId,"",this.totalResults, true).subscribe(stakeholder => {
                      this.stakeholder = stakeholder;

                    }));
                    this.subscriptions.push(this._searchResearchResultsService.numOfResearchOutcomes(this.param + ' and (resultbestaccessright exact "Open Access") and (peerreviewed exact "true")', properties, null).subscribe(res => {
                      this.openResults = +res;
                    }));
                  }
                }
              }
              this.search();

          /*  } else {
              this._router.navigate([properties.errorLink]);
            }
          }));*/
        }
      } else {
        this.stakeholder = null;
        this.author = null;
        this._customFilterService.setCustomFilter([]);
        this.title = 'Researcher Monitors';
        this.description = 'Researcher Monitors';
        this.setMetadata();
      }
    });
  }

  ngOnDestroy() {
    super.ngOnDestroy();
    this.layoutService.setRootClass(null);
  }

  getPercentage(){
    let num = (this.openResults/this.totalResults)*100;
    return num == 100?100:num.toPrecision(2);
  }
}
