import {ChangeDetectorRef, Component, ElementRef, Input, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Meta, Title} from '@angular/platform-browser';

import {ProjectService} from './project.service';
import {ProjectInfo} from '../../utils/entities/projectInfo';
import {RouterHelper} from '../../utils/routerHelper.class';

import {FetchResearchResults} from '../../utils/fetchEntitiesClasses/fetchResearchResults.class';
import {SearchResearchResultsService} from '../../services/searchResearchResults.service';

import {ModalLoading} from '../../utils/modal/loading.component';

import {ReportsService} from '../../services/reports.service';
import {ErrorCodes} from '../../utils/properties/errorCodes'

import {PiwikService} from '../../utils/piwik/piwik.service';
import {EnvProperties} from '../../utils/properties/env-properties';
import {SEOService} from '../../sharedComponents/SEO/SEO.service';
import {HelperFunctions} from "../../utils/HelperFunctions.class";
import {HelperService} from "../../utils/helper/helper.service";
import {Location} from "@angular/common";
import {HtmlProjectReportService} from "../htmlProjectReport/htmlProjectReport.service";
import {StringUtils} from "../../utils/string-utils.class";
import {ResultPreview} from "../../utils/result-preview/result-preview";
import {SearchResult} from "../../utils/entities/searchResult";
import {IndexInfoService} from "../../utils/indexInfo.service";
import {Subscriber, Subscription, zip} from "rxjs";
import {properties} from "../../../../environments/environment";
import {Option} from "../../sharedComponents/input/input.component";
import {OpenaireEntities} from "../../utils/properties/searchFields";
import {MetricsService} from '../../services/metrics.service';
import {NumberUtils} from '../../utils/number-utils.class';
import {LayoutService} from '../../dashboard/sharedComponents/sidebar/layout.service';
import {FullScreenModalComponent} from '../../utils/modal/full-screen-modal/full-screen-modal.component';

declare var ResizeObserver;

@Component({
  selector: 'project',
  templateUrl: 'project.component.html',
})

export class ProjectComponent {
  public referrer: string;
  public prevPath: string;
  @Input() communityId = null;
  public projectInfo: ProjectInfo;
  public projectId: string;
  public projectName: string;

  // Metrics tab variables
  public metricsClicked: boolean;
  public viewsFrameUrl: string;
  public downloadsFrameUrl: string;
  /** @deprecated*/
  public totalViews: number = null;
  /** @deprecated*/
  public totalDownloads: number = null;
  public hasViews: boolean = false;
  public hasDownloads: boolean = false;
  // public pageViews: number;

  // Statistics tab variables
  public statsClicked: boolean;
  public chartScientificResultsUrl: string;
  public chartAccessModeUrl: string;
  public chartDatasourcesUrl: string;

  // Clipboard variable for HTML dynamic content
  public clipboard;

  public project;

  // CSV variables
  public downloadURLAPI: string;
  public csvParams: string;

  // HTML (download) variables
  public header1: string = "";
  public header2: string = "";
  public htmlResultDownload: string = "";

  // Message variables
  public warningMessage = "";
  public errorMessage = "";
  public showLoading: boolean = true;

  // Active tab variable for responsiveness
  public activeTab: string = "";

  // @ViewChild('statisticsModal') statisticsModal;
  // @ViewChild('linkProjectModal') linkProjectModal;
  @ViewChild('embedResultsModal') embedResultsModal;
	@ViewChild('embedResultsFsModal') embedResultsFsModal: FullScreenModalComponent;
  @ViewChild('downloadReportModal') downloadReportModal;
	@ViewChild('downloadReportFsModal') downloadReportFsModal: FullScreenModalComponent;
  @ViewChild('addThisModal') addThisModal;
	@ViewChild('addThisFsModal') addThisFsModal: FullScreenModalComponent;

  // Request results for publications, research data and software only the one time (first time tab is clicked)
  private reloadPublications: boolean = true;
  private reloadDatasets: boolean = true;
  private reloadSoftware: boolean = true;
  private reloadOrps: boolean = true;
  private reloadDmps: boolean = true;

  // Variables for entity selections on the right column
  public embed_research_results_type: string = "result";
  public download_research_results_type: string = "";

  // Variables for publications, research data, software tabs
  public fetchPublications: FetchResearchResults;
  public fetchDatasets: FetchResearchResults;
  public fetchSoftware: FetchResearchResults;
  public fetchOrps: FetchResearchResults;
  public fetchDmps: FetchResearchResults;
  public searchNumber: number = 5;

  public routerHelper: RouterHelper = new RouterHelper();
  public errorCodes: ErrorCodes = new ErrorCodes();
  public pageContents = null;
  public divContents = null;

  public indexUpdateDate: Date;
  public showFeedback: boolean;
  public feedbackFields: string [] = [
    'Title', 'Funding Information', 'Duration',
    OpenaireEntities.ORGANIZATIONS, 'Other'];

  @ViewChild(ModalLoading) loading: ModalLoading;
  // Alert box when something is wrong with CSV requests
  @ViewChild('AlertModalCsvError') alertCsvError;

  // Description variables for view more/less functionality
  public thresholdDescription: number = 670;
  public showNumDescription: number = 670;

  // // Organizations variables for view more/less functionality
  // public thresholdOrganizations: number = 20;
  // public showNumOrganizations: number = 20;
  /*Show all organizations*/
  public viewAllOrganizations: boolean = false;
  public lessBtnOrganizations: boolean = false;
  public thresholdOrganizations: number = 20;
  @ViewChild('organizationsModal') organizationsModal;


  public resultTypesForEmbedding: Option[]=[
    {label: "All "+OpenaireEntities.RESULTS, value: "result"},
    {label: OpenaireEntities.PUBLICATIONS, value: "publication"},
    {label: OpenaireEntities.DATASETS, value: "dataset"},
    {label: OpenaireEntities.SOFTWARE, value: "software"},
    {label: OpenaireEntities.OTHER, value: "other"}];

  public resultTypesForDownloading: Option[]=[
    {label: "All "+OpenaireEntities.RESULTS, value: "results", disabled: true},
    {label: OpenaireEntities.PUBLICATIONS, value: "publications", disabled: true},
    {label: OpenaireEntities.DATASETS, value: "datasets", disabled: true},
    {label: OpenaireEntities.SOFTWARE, value: "software", disabled: true},
    {label: OpenaireEntities.OTHER, value: "other", disabled: true}];

  public offset: number;
  public stickyHeader: boolean = false;
  public graph_offset: number = 0;
  public graph_height: number = 0;
  @ViewChild("graph_and_feedback") graph_and_feedback;

	@ViewChild("descriptionDiv") descriptionDiv: ElementRef;
	@ViewChild('descriptionModal') descriptionModal;

  // public shouldSticky: boolean = true;

  subscriptions = [];
	private sub: Subscription;
  properties: EnvProperties;
  public openaireEntities = OpenaireEntities;

	public isMobile: boolean = false;
	public mobileContent: "info" | "metrics" | "actions" = "info";
	public tabMobile: string = "";
	public viewAllMobile: string = "";
	// Full screen modals for small screens (mobile)
  @ViewChild('summaryFsModal') summaryFsModal: FullScreenModalComponent;
	@ViewChild('publicationsFsModal') publicationsFsModal: FullScreenModalComponent;
	@ViewChild('datasetsFsModal') datasetsFsModal: FullScreenModalComponent;
	@ViewChild('softwareFsModal') softwareFsModal: FullScreenModalComponent;
	@ViewChild('otherFsModal') otherFsModal: FullScreenModalComponent;
	@ViewChild('dmpsFsModal') dmpsFsModal: FullScreenModalComponent;
	@ViewChild('statisticsFsModal') statisticsFsModal: FullScreenModalComponent;

  constructor(private  route: ActivatedRoute,
              private _router: Router,
              private _location: Location,
              private _meta: Meta,
              private _title: Title,
              private seoService: SEOService,
              private _piwikService: PiwikService,
              private helper: HelperService,
              private _projectService: ProjectService,
              private _searchResearchResultsService: SearchResearchResultsService,
              private _reportsService: ReportsService,
              private htmlService: HtmlProjectReportService,
              private indexInfoService: IndexInfoService,
							private metricsService: MetricsService,
              private cdr: ChangeDetectorRef,
							private layoutService: LayoutService) {}

  ngOnInit() {
		this.subscriptions.push(this.layoutService.isMobile.subscribe(isMobile => {
      this.isMobile = isMobile;
    }));
		this.properties = properties;
		if (typeof document !== 'undefined') {
			this.subscriptions.push(this.indexInfoService.getLastIndexDate(this.properties).subscribe(lastIndexUpdate => {
				if (lastIndexUpdate) {
					this.indexUpdateDate = new Date(lastIndexUpdate);
				}
			}));
		}
    if(properties.adminToolsPortalType !== "explore") {
      //this.getDivContents();
      this.getPageContents();
    }
		this.updateUrl(this.properties.domain + this.properties.baseLink + this._router.url);
		this.seoService.createLinkForCanonicalURL(this.properties.domain +this.properties.baseLink +  this._router.url);
    this.subscriptions.push(this.route.queryParams.subscribe(params => {
      this.stickyHeader = false;
      this.metricsClicked = false;
      this.statsClicked = false;
      this.fetchPublications = new FetchResearchResults(this._searchResearchResultsService);
      this.fetchDatasets = new FetchResearchResults(this._searchResearchResultsService);
      this.fetchSoftware = new FetchResearchResults(this._searchResearchResultsService);
      this.fetchOrps = new FetchResearchResults(this._searchResearchResultsService);
      this.fetchDmps = new FetchResearchResults(this._searchResearchResultsService);
      var title = OpenaireEntities.PROJECT;
      var description = "";

      this.header1 = "";

      this.updateTitle(title);
      this.updateDescription(description);

      if(params["return_path"]) {
        this.prevPath = params["return_path"] + (params["search_params"] ? ("?"+params["search_params"]) : "");
      }
      if((typeof document !== 'undefined') && document.referrer) {
        this.referrer = document.referrer;
      }

      this.projectId = params['projectId'];
      var grantId = params['grantId'];
      var funder = params['funder'];


      if (this.projectId  && StringUtils.isOpenAIREID(this.projectId)) {
        this.getProjectInfo(this.projectId);
        this.actionsAfterLoadId();
      } else if (grantId && funder) {
        this.getProjectInfoByGrantId(grantId, funder);
      } else {

        this.showLoading = false;
        this._router.navigate([this.properties.errorLink], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
        //this.warningMessage = "No valid project id";
      }

      this.downloadURLAPI = this.properties.csvAPIURL;

      this.createClipboard();
    }));
  }

  ngAfterViewInit() {
    if (typeof document !== 'undefined') {
      if(document.getElementById("main-menu")) {
        this.offset = Number.parseInt(getComputedStyle(document.documentElement).getPropertyValue('--header-height'));
      } else {
        this.offset = 0;
      }
      // let bottom = document.getElementById('bottom');
      // if(bottom) {
      //   let observer = new IntersectionObserver(entries => {
      //     entries.forEach(entry => {
      //       this.shouldSticky = !entry.isIntersecting;
      //     })
      //   });
      //   this.subscriptions.push(observer);
      //   observer.observe(bottom);
      // }
      if(this.graph_and_feedback) {
        this.observeGraphAndFeedback();
      }
    }
  }

  ngAfterContentChecked() {
    if(this.graph_and_feedback && typeof document !== 'undefined') {
      this.graph_offset = this.calcGraphOffset(this.graph_and_feedback.nativeElement);
    }
  }

	get showViewMoreButton():boolean {
		return !!this.descriptionDiv && (this.descriptionDiv.nativeElement.clientHeight >= 10 * 21);
	}

  public observeGraphAndFeedback() {
    let resizeObs = new ResizeObserver(entries => {
      entries.forEach(entry => {
        setTimeout(() => {
          // console.log(entry);
          this.graph_offset = this.calcGraphOffset(entry.target);
          this.cdr.detectChanges();
        });
      })
    });
    this.subscriptions.push(resizeObs);
    resizeObs.observe(this.graph_and_feedback.nativeElement);
  }

  calcGraphOffset(element) {
    this.graph_height = element.offsetHeight;
    return window.innerHeight-this.graph_height;
  }

  public getFileNameType(type: string) {
    return StringUtils.getEntityFileName(type);
  }

  public getCsvParams(type: string) {
    // if(type == "results") {
    //   type = "publications&type=datasets&type=software&type=other";
    // }
    return "?format=csv-special&type="+type+"&fq=(relprojectid exact \"" + this.projectId + "\")";
  }

  private getPageContents() {
    if(this.communityId) {
      this.subscriptions.push(this.helper.getPageHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
        this.pageContents = contents;
      }));
    }
  }

  private getDivContents() {
    if(this.communityId) {
      this.subscriptions.push(this.helper.getDivHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
        this.divContents = contents;
      }));
    }
  }

  getDynamicContent(type: string) {
    return  "<script type=\"text/javascript\">"
      + "\n<!--"
      + "\ndocument.write('<div id=\"oa_widget\"></div>');"
      + "\ndocument.write('<script type=\"text/javascript\""
      + " src=\"" + this.properties.widgetLink
      + this.projectId + "&type="
      + type
      + "\"></script>');"
      + "\n-->"
      + "\n</script>";
  }

  actionsAfterLoadId() {
    //this.getProjectInfo(this.projectId);
    //this.searchPublications();

    if (typeof document !== 'undefined') {
      this.fetchPublications.getNumForEntity("publication", "project", this.projectId, this.properties);
      this.fetchDatasets.getNumForEntity("dataset", "project", this.projectId, this.properties);
      this.fetchSoftware.getNumForEntity("software", "project", this.projectId, this.properties);
      this.fetchOrps.getNumForEntity("other", "project", this.projectId, this.properties);
      this.searchDmps(1, this.searchNumber);
    }
  }

  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      } else if ((typeof ResizeObserver != 'undefined' && subscription instanceof ResizeObserver) ||
          (typeof IntersectionObserver != 'undefined' && subscription instanceof IntersectionObserver)) {
        subscription.disconnect();
      }
    });
    this.fetchDatasets.clearSubscriptions();
    this.fetchPublications.clearSubscriptions();
    this.fetchSoftware.clearSubscriptions();
    this.fetchOrps.clearSubscriptions();
    this.fetchDmps.clearSubscriptions();
  }

  private createClipboard() {
    if (typeof window !== 'undefined') {
      delete this.clipboard;
      let Clipboard;
      Clipboard = require('clipboard');
      this.clipboard = new Clipboard('.clipboard_btn');
    }
  }

  public searchPublications(page: number, size: number) {
    if (this.reloadPublications &&
      (this.fetchPublications.searchUtils.status == this.errorCodes.LOADING ||
        (this.fetchPublications.searchUtils.status == this.errorCodes.DONE && this.fetchPublications.searchUtils.totalResults > 0)
      )
    ) {
      this.fetchPublications.getResultsForEntity("publication", "project", this.projectId, page, size, this.properties);
    }
    this.reloadPublications = false;
  }

  public searchDmps(page: number, size: number) {
    if (this.reloadDmps &&
      (this.fetchDmps.searchUtils.status == this.errorCodes.LOADING ||
        (this.fetchDmps.searchUtils.status == this.errorCodes.DONE && this.fetchDmps.searchUtils.totalResults > 0)
      )
    ) {
      this.fetchDmps.getDmps("project", this.projectId, page, size, this.properties);
    }
    this.reloadDmps = false;
  }

  public searchDatasets(page: number, size: number) {
    if (this.reloadDatasets &&
      (this.fetchDatasets.searchUtils.status == this.errorCodes.LOADING ||
        (this.fetchDatasets.searchUtils.status == this.errorCodes.DONE && this.fetchDatasets.searchUtils.totalResults > 0)
      )
    ) {
      this.fetchDatasets.getResultsForEntity("dataset", "project", this.projectId, page, size, this.properties);
    }
    this.reloadDatasets = false;
  }

  private searchSoftware(page: number, size: number) {
    if (this.reloadSoftware &&
      (this.fetchSoftware.searchUtils.status == this.errorCodes.LOADING ||
        (this.fetchSoftware.searchUtils.status == this.errorCodes.DONE && this.fetchSoftware.searchUtils.totalResults > 0)
      )
    ) {
      this.fetchSoftware.getResultsForEntity("software", "project", this.projectId, page, size, this.properties);
    }
    this.reloadSoftware = false;
  }

  private searchOrps(page: number, size: number) {
    if (this.reloadOrps &&
      (this.fetchOrps.searchUtils.status == this.errorCodes.LOADING ||
        (this.fetchOrps.searchUtils.status == this.errorCodes.DONE && this.fetchOrps.searchUtils.totalResults > 0)
      )
    ) {
      this.fetchOrps.getResultsForEntity("other", "project", this.projectId, page, size, this.properties);
    }
    this.reloadOrps = false;
  }

  private getProjectInfo(id: string) {
    this.warningMessage = '';
    this.errorMessage = "";
    this.showLoading = true;

    this.projectInfo = null;

    this.subscriptions.push(this._projectService.getProjectInfo(id, this.properties).subscribe(
      data => {
        this.projectInfo = data;
        this.projectInfo.id = this.projectId;

        this.actionsAfterGettingProjectInfo();
      },
      err => {
        //console.log(err);
        this.handleError("Error getting project for id: " + this.projectId, err);
        if(err.status == 404) {
          this._router.navigate([this.properties.errorLink], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
        }else if(err.name == "TimeoutError"){
          this.errorMessage = 'An error occurred please try again later';
        }else {
          this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this.properties.searchLinkToProjects);
          this.errorMessage = 'No '+OpenaireEntities.PROJECT+' found';
        }
        this.showLoading = false;
      }
    ));
  }

  private getProjectInfoByGrantId(grantId: string, funder: string) {
    this.warningMessage = '';
    this.errorMessage = "";
    this.showLoading = true;

    this.projectInfo = null;

    this.subscriptions.push(this._projectService.getProjectInfoByGrantId(grantId, funder, this.properties).subscribe(
      data => {
				this.projectInfo = data;

        this.actionsAfterGettingProjectInfo();
        this.projectId = this.projectInfo.id;
        this.actionsAfterLoadId();
      },
      err => {
        //console.log(err);
        this.handleError("Error getting project for grant id: " + grantId + " and funder: " + funder, err);
        if(err.status == 404) {
          this._router.navigate([this.properties.errorLink], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
        }else if(err.name == "TimeoutError"){
          this.errorMessage = 'An error occurred please try again later';
        }else {
          this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this.properties.searchLinkToProjects);
          this.errorMessage = 'No project found';
        }
        this.showLoading = false;
      }
    ));
  }

  actionsAfterGettingProjectInfo() {
    this.projectName = this.projectInfo.acronym;
    if (this.projectName == undefined || this.projectName == '') {
      this.projectName = this.projectInfo.title;
    }
    this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this._router.url);
    this.updateTitle(this.projectName);
    // this.updateDescription(this.projectInfo.description?this.projectInfo.description: ("project" + (this.projectInfo.title?"," + this.projectInfo.title:"") + (this.projectInfo.funding && this.projectInfo.funding.funderName?", funder: " + this.projectInfo.funding.funderName:"") + (this.projectInfo.acronym?"," + this.projectInfo.acronym:"")));
    this.updateDescription((this.projectInfo.description ? (this.projectInfo.description.substr(0,157)  + (this.projectInfo.description.substr(0,157).length == 157?"...":"")) : (this.projectInfo.title)));
    this.subscriptions.push(this._piwikService.trackView(this.properties, this.projectName).subscribe());
    this.project = {
      funderId: "",
      funderName: ((this.projectInfo.funding) ? this.projectInfo.funding.funderShortName: ''),
      projectId: this.projectId,
      projectName: this.projectInfo.title,
      projectAcronym: this.projectInfo.acronym,
      startDate: this.projectInfo.startDate,
      endDate: this.projectInfo.endDate
    };

    this.hasViews = false;
    this.hasDownloads = false;

    // ensure that if the API call to index does not have metrics, we get them from old metrics service call
    if(this.projectInfo && !this.projectInfo.measure) {
      this.getMetrics();
    } else if(this.projectInfo && this.projectInfo.measure && this.projectInfo.measure.counts) {
      this.projectInfo.measure.counts.forEach(measure => {
        if(measure.name == "views" && measure.value > 0) {
          this.hasViews = true;
        }
        if(measure.name == "downloads" && measure.value > 0) {
          this.hasDownloads = true;
        }
      })
    }
    //old
    // this.viewsFrameUrl = this.properties.framesAPIURL + 'merge.php?com=query&data=[{"query":"projRepoViews","projTitle":"' + this.projectId + '","table":"","fields":[{"fld":"sum","agg":"sum","type":"column","yaxis":1,"c":false}],"xaxis":{"name":"month","agg":"sum"},"group":"","color":"","type":"chart","size":200,"sort":"xaxis","xStyle":{"r":-30,"s":"6","l":"-","ft":"-","wt":"-"},"title":"","subtitle":"","xaxistitle":"","yaxisheaders":["Monthly views"],"generalxaxis":"","theme":0,"in":[]}]&info_types=["column"]&stacking=&steps=false&fontFamily=Courier&spacing=[5,0,0,0]&style=[{"color":"rgba(0, 0, 0, 1)","size":"18"},{"color":"rgba(0, 0, 0, 1)","size":"18"},{"color":"000000","size":""},{"color":"000000","size":""}]&backgroundColor=rgba(255,255,255,1)&colors[]=rgba(124, 181, 236, 1)&colors[]=rgba(67, 67, 72, 1)&colors[]=rgba(144, 237, 125, 1)&colors[]=rgba(247, 163, 92, 1)&colors[]=rgba(128, 133, 233, 1)&colors[]=rgba(241, 92, 128, 1)&colors[]=rgba(228, 211, 84, 1)&colors[]=rgba(43, 144, 143, 1)&colors[]=rgba(244, 91, 91, 1)&colors[]=rgba(145, 232, 225, 1)&xlinew=0&ylinew=1&legends=true&tooltips=true&persistent=false';
    //
    // this.downloadsFrameUrl = this.properties.framesAPIURL + 'merge.php?com=query&data=[{"query":"projRepoDownloads","projTitle":"' + this.projectId + '","table":"","fields":[{"fld":"sum","agg":"sum","type":"column","yaxis":1,"c":false}],"xaxis":{"name":"month","agg":"sum"},"group":"","color":"","type":"chart","size":200,"sort":"xaxis","xStyle":{"r":-30,"s":"6","l":"-","ft":"-","wt":"-"},"title":"","subtitle":"","xaxistitle":"","yaxisheaders":["Monthly downloads"],"generalxaxis":"","theme":0,"in":[]}]&info_types=["column"]&stacking=&steps=false&fontFamily=Courier&spacing=[5,0,0,0]&style=[{"color":"rgba(0, 0, 0, 1)","size":"18"},{"color":"rgba(0, 0, 0, 1)","size":"18"},{"color":"000000","size":""},{"color":"000000","size":""}]&backgroundColor=rgba(255,255,255,1)&colors[]=rgba(124, 181, 236, 1)&colors[]=rgba(67, 67, 72, 1)&colors[]=rgba(144, 237, 125, 1)&colors[]=rgba(247, 163, 92, 1)&colors[]=rgba(128, 133, 233, 1)&colors[]=rgba(241, 92, 128, 1)&colors[]=rgba(228, 211, 84, 1)&colors[]=rgba(43, 144, 143, 1)&colors[]=rgba(244, 91, 91, 1)&colors[]=rgba(145, 232, 225, 1)&xlinew=0&ylinew=1&legends=true&tooltips=true&persistent=false';
    //new
    this.viewsFrameUrl = this.properties.statisticsFrameNewAPIURL + 'chart?json='  + encodeURIComponent('{"library":"HighCharts","chartDescription":{"queries":[{"name":"Monthly views","type":"column","query":{"name":"usagestats.projects.views.monthly", "parameters":["' + this.projectId + '"], "profile":"OpenAIRE All-inclusive" }}],"chart":{"backgroundColor":"#FFFFFFFF","borderColor":"#335cadff","borderRadius":0,"borderWidth":0,"plotBorderColor":"#ccccccff","plotBorderWidth":0},"title":{"text":"Monthly views"},"subtitle":{},"yAxis":{"title":{"text":""}},"xAxis":{"title":{}},"lang":{"noData":"No Data available for the Query"},"exporting":{"enabled":false},"plotOptions":{"series":{"dataLabels":{"enabled":false}}},"legend":{"enabled":false},"credits":{"href":null,"enabled":true,"text":""}}}');
    this.downloadsFrameUrl = this.properties.statisticsFrameNewAPIURL + 'chart?json='  +
      encodeURIComponent('{"library":"HighCharts","chartDescription":{"queries":[{"name":"Monthly downloads","type":"column","query":{"name":"usagestats.projects.downloads.monthly", "parameters":["' + this.projectId + '"], "profile":"OpenAIRE All-inclusive" }}],"chart":{"backgroundColor":"#FFFFFFFF","borderColor":"#335cadff","borderRadius":0,"borderWidth":0,"plotBorderColor":"#ccccccff","plotBorderWidth":0},"title":{"text":"Monthly downloads"},"subtitle":{},"yAxis":{"title":{"text":""}},"xAxis":{"title":{}},"lang":{"noData":"No Data available for the Query"},"exporting":{"enabled":false},"plotOptions":{"series":{"dataLabels":{"enabled":false}}},"legend":{"enabled":false},"credits":{"href":null,"enabled":true,"text":""}}}');
    //stats tab charts
    if (this.properties.useNewStatistisTool) {
      this.chartScientificResultsUrl = this.properties.statisticsFrameNewAPIURL +
        'chart?json='+StringUtils.URIEncode('{"library":"HighCharts","chartDescription":{"queries":[{"name":"'+OpenaireEntities.RESULTS+'","type":"column","query":{"name":"projScient","parameters":["'+this.projectId+'"]}}],"chart":{"backgroundColor":"#FFFFFFFF","borderColor":"#335cadff","borderRadius":0,"borderWidth":0,"plotBorderColor":"#ccccccff","plotBorderWidth":0},"title":{"text":"Produced '+OpenaireEntities.RESULTS+' per year"},"subtitle":{},"yAxis":{"title":{"text":"'+OpenaireEntities.RESULTS+'"}},"xAxis":{"title":{"text":"Year"}},"lang":{"noData":"No Data available for the Query"},"exporting":{"enabled":false},"plotOptions":{"series":{"dataLabels":{"enabled":false}}},"legend":{"enabled":true,"align":"center","verticalAlign":"bottom","layout":"horizontal"},"credits":{"href":null,"enabled":true,"text":"Created by OpenAIRE via HighCharts"}}}');
      this.chartAccessModeUrl =  this.properties.statisticsFrameNewAPIURL +
        'chart?json='+StringUtils.URIEncode(
        '{"library":"HighCharts","chartDescription":{"queries":[{"name":"'+OpenaireEntities.RESULTS+'","type":"pie","query":{"name":"projOA","parameters":["'+this.projectId+'"]}}],"chart":{"backgroundColor":"#FFFFFFFF","borderColor":"#335cadff","borderRadius":0,"borderWidth":0,"plotBorderColor":"#ccccccff","plotBorderWidth":0},"title":{"text":"Access mode of '+OpenaireEntities.RESULTS+'"},"subtitle":{},"yAxis":{"title":{"text":"'+OpenaireEntities.RESULTS+'"}},"xAxis":{"title":{"text":"Access mode"}},"lang":{"noData":"No Data available for the Query"},"exporting":{"enabled":false},"plotOptions":{"series":{"dataLabels":{"enabled":false}}},"legend":{"enabled":true,"align":"center","verticalAlign":"bottom","layout":"horizontal"},"credits":{"href":null,"enabled":true,"text":"Created by OpenAIRE via HighCharts"}}}');
      this.chartDatasourcesUrl =  this.properties.statisticsFrameNewAPIURL +
        'chart?json='+StringUtils.URIEncode(
        '{"library":"HighCharts","chartDescription":{"queries":[{"name":"'+OpenaireEntities.RESULTS+'","type":"bar","query":{"name":"projPubsRepos","parameters":["'+this.projectId+'"]}}],"chart":{"backgroundColor":"#FFFFFFFF","borderColor":"#335cadff","borderRadius":0,"borderWidth":0,"plotBorderColor":"#ccccccff","plotBorderWidth":0},"title":{"text":"'+OpenaireEntities.RESULTS+' per datasource"},"subtitle":{},"yAxis":{"title":{"text":"'+OpenaireEntities.RESULTS+'"}},"xAxis":{"title":{"text":"Datasource"}},"lang":{"noData":"No Data available for the Query"},"exporting":{"enabled":false},"plotOptions":{"series":{"dataLabels":{"enabled":true}}},"legend":{"enabled":true,"align":"center","verticalAlign":"bottom","layout":"horizontal"},"credits":{"href":null,"enabled":true,"text":"Created by OpenAIRE via HighCharts"}}}');
    } else {
      this.chartScientificResultsUrl = this.properties.statisticsFrameAPIURL + 'chart.php?com=query&persistent=false&data={"query":"projScient","projTitle":"' + this.projectId + '", "table": "result", "fields": [{"fld": "number", "agg": "count", "type": "spline", "yaxis":1, "c":false}], "xaxis":{"name": "result_classifications-type", "agg": "avg"}, "group": "", "color": "", "type": "chart", "size":30, "sort": "xaxis", "xStyle":{"r": "-", "s": "-", "l": "-", "ft": "-", "wt": "-"}, "yaxisheaders": [""], "fieldsheaders": ["'+OpenaireEntities.RESULTS+'"], "in": [], "filters": [{"name": "result_datasources-datasource-name", "values": [" "], "to": "-1"}], "having": [], "incfilters": [], "inchaving": [], "title": "", "subtitle": "", "xaxistitle": ""}&w=90%&h=90%';
      this.chartAccessModeUrl = this.properties.statisticsFrameAPIURL + 'chart.php?com=query&persistent=false&data={"query":"projOA","projTitle":"' + this.projectId + '", "table": "result", "fields": [{"fld": "number", "agg": "count", "type": "pie", "yaxis":1, "c":false}], "xaxis":{"name": "result_classifications-type", "agg": "avg"}, "group": "", "color": "", "type": "chart", "size":30, "sort": "xaxis", "xStyle":{"r": "-", "s": "-", "l": "-", "ft": "-", "wt": "-"}, "yaxisheaders": [""], "fieldsheaders": ["'+OpenaireEntities.RESULTS+'"], "in": [], "filters": [{"name": "result_datasources-datasource-name", "values": [" "], "to": "-1"}], "having": [], "incfilters": [], "inchaving": [], "title": "", "subtitle": "", "xaxistitle": ""}&w=90%&h=90%';
      this.chartDatasourcesUrl = this.properties.statisticsFrameAPIURL + 'chart.php?com=query&persistent=false&data={"query":"projPubsRepos","projTitle":"' + this.projectId + '", "table": "result", "fields": [{"fld": "number", "agg": "count", "type": "bar", "yaxis":1, "c":false}], "xaxis":{"name": "result_classifications-type", "agg": "avg"}, "group": "", "color": "", "type": "chart", "size":30, "sort": "xaxis", "xStyle":{"r": "-", "s": "-", "l": "-", "ft": "-", "wt": "-"}, "yaxisheaders": [""], "fieldsheaders": ["'+OpenaireEntities.RESULTS+'"], "in": [], "filters": [{"name": "result_datasources-datasource-name", "values": [" "], "to": "-1"}], "having": [], "incfilters": [], "inchaving": [], "title": "", "subtitle": "", "xaxistitle": ""}&w=90%&h=90%';
    }

    this.showLoading = false;
    this.cdr.detectChanges();
  }

  public downloadCsvFile(url: string, filename: string) {
    this.openLoading();
    this.setMessageLoading("Downloading CSV file");

    this.subscriptions.push(this._reportsService.downloadCSVFile(url).subscribe(
      data => {
        this.closeLoading();

        let url = window.URL.createObjectURL(data);
        this.download(url, filename+".csv");
        this.subscriptions.push(this._piwikService.trackDownload(this.properties, "DownloadCSV"+filename).subscribe());
      },
      error => {
        //console.log("Error downloading the file.");
        this.handleError("Error downloading file: " + filename, error);

        this.closeLoading();
        this.confirmOpenFileDownloadError("CSV");
      }/*,
            () => console.log('Completed file download.')*/
    ));
  }

  public metricsResults($event) {
    this.totalViews = $event.totalViews;
    this.totalDownloads = $event.totalDownloads;
    // this.pageViews = $event.pageViews;
  }

	private getMetrics() {
		let obs;
		obs = zip(this.metricsService.getMetricsNumber(this.projectId, "usagestats.projects.views", this.properties),
          this.metricsService.getMetricsNumber(this.projectId, "usagestats.projects.downloads", this.properties));
		this.sub = obs.subscribe(data => {
      if((data[0] && data[0] > 0) || (data[1] && data[1] > 0)) {
        this.projectInfo.measure = {counts: []};
        if(data[0] && data[0] > 0) {
          this.projectInfo.measure.counts.push({name: 'views', order: 0, icon: 'visibility', value: data[0]});
          this.hasViews = true;
        }
        if(data[1] && data[1] > 0) {
          this.projectInfo.measure.counts.push({name: 'downloads', order: 1, icon: 'downloads', value: data[1]});
          this.hasDownloads = true;
        }

        this.cdr.detectChanges();
      }
			// this.totalViews = data[0];
			// this.totalDownloads = data[1];
		});
	}

  public get hasMetrics(): boolean {
    // return !(this.totalViews != null && this.totalDownloads != null) || this.totalViews > 0 || this.totalDownloads > 0;
    return this.projectInfo.measure?.counts?.length > 0;
  }

  public viewAllOrganizationsClick() {
    this.viewAllOrganizations = true;
    if(this.projectInfo.organizations.length <= this.thresholdOrganizations*2) {
      this.lessBtnOrganizations = true;
    } else {
      this.openOrganizationsModal();
    }
  }

	public viewAllOrganizationsMobileClicked() {
    this.summaryFsModal.title += " - Partners";
    this.summaryFsModal.back = true;
    this.lessBtnOrganizations = true;
    this.viewAllMobile = "organizations";
  }

  public openOrganizationsModal() {
    this.organizationsModal.cancelButton = false;
    this.organizationsModal.okButton = false;
    this.organizationsModal.alertTitle = "Partners";
    this.organizationsModal.open();
  }

  public openAddThisModal() {
    this.addThisModal.cancelButton = false;
    this.addThisModal.okButton = false;
    this.addThisModal.alertTitle = "Share this "+OpenaireEntities.PROJECT+" in your social networks";
    this.addThisModal.open();
  }

  public openEmbedResultsModal() {
    this.embedResultsModal.cancelButton = false;
    this.embedResultsModal.okButton = false;
    this.embedResultsModal.alertTitle = "Embed results";
    this.embedResultsModal.open();
  }

  public openDownloadReportModal() {
    if(this.fetchPublications.searchUtils.totalResults > 0 || this.fetchDatasets.searchUtils.totalResults > 0 ||
       this.fetchSoftware.searchUtils.totalResults > 0 || this.fetchOrps.searchUtils.totalResults > 0) {
      this.download_research_results_type = "results";
    }
    this.downloadReportModal.cancelButton = false;
    this.downloadReportModal.okButton = false;
    this.downloadReportModal.alertTitle = "Download report";
    this.downloadReportModal.open();
  }


  public closeDownloadReportModal() {
    this.downloadReportModal.cancel();
  }

  private createHeaders(type: string) {
    this.openLoading();
    this.setMessageLoading("Downloading HTML file");

    if(!this.header1) {
      this.createHeader1();
    }

    if (type == "publications") {
      this.header2 = this.fetchPublications.searchUtils.totalResults.toLocaleString('en-US') + " "+OpenaireEntities.PUBLICATIONS;
    } else if (type == "datasets") {
      this.header2 = this.fetchDatasets.searchUtils.totalResults.toLocaleString('en-US') + " "+OpenaireEntities.DATASETS;
    } else if (type == "software") {
      this.header2 = this.fetchSoftware.searchUtils.totalResults.toLocaleString('en-US') + " "+OpenaireEntities.SOFTWARE;
    } else if (type == "other") {
      this.header2 = this.fetchOrps.searchUtils.totalResults.toLocaleString('en-US') + " "+OpenaireEntities.OTHER;
    } else if (type == "results") {
      let totalResults: number = (+this.fetchPublications.searchUtils.totalResults) +
        (+this.fetchDatasets.searchUtils.totalResults) +
        (+this.fetchSoftware.searchUtils.totalResults) +
        (+this.fetchOrps.searchUtils.totalResults);

      this.header2 = totalResults.toLocaleString('en-US') + " "+OpenaireEntities.RESULTS;
    }
  }

  private createHtmlFile(type: string, filename: string) {
    let intro: string = '<!doctype html>';
    intro += '<html lang="en-gb" dir="ltr" vocab="http://schema.org/">';
    intro += '<head>';
    intro += '<title>' + this.header1 + '</title>';
    intro += '</head>';

    if (typeof window !== 'undefined') {
      this.subscriptions.push(this.htmlService.getHTML(this.projectId, type, this.properties.csvAPIURL).subscribe(
        data => {
          //console.info(data);
          this.htmlResultDownload = intro + '<body><div>' + this.header1 + '</div><div><h4>' + this.header2 + '</h4></div>';
          this.htmlResultDownload += "<table><thead><tr> <th>Type</th><th>Title</th><th>Authors</th><th>Publication Year</th><th>DOI</th><th>Permanent Identifier</th><th>Publication type</th><th>Journal</th><th>Project Name (GA Number)</th><th>Access Mode</th></tr></thead><tbody>" + data + "</tbody></table>";
          this.htmlResultDownload += '</body></html>';

          //console.info(this.htmlResultDownload);
          this.closeLoading();

          let url = window.URL.createObjectURL(new Blob([this.htmlResultDownload], { type: 'text/html' }));
          this.download(url, filename+".html");

          this.subscriptions.push(this._piwikService.trackDownload(this.properties, "DownloadHTML"+filename).subscribe());
        },
        err => {
          this.handleError("Error getting html for id: " + this.projectId, err);
          //this.errorMessage = 'Service not available';
          this.closeLoading();
          this.confirmOpenFileDownloadError("HTML");
        }
      ));
    } else {
      this.closeLoading();
      this.confirmOpenFileDownloadError("HTML");
    }
  }

  downloadHtmlFile(type: string, filename: string) {
    this.createHeaders(type);
    this.createHtmlFile(type, filename);
  }

  createHeader1() {
    // if (title != undefined && title != "") {
    //   this.header1 += title;
    // }
    // if ((title != undefined && title != "") &&
    //   ((acronym != undefined && acronym != "") ||
    //     (code != undefined && code != ""))) {
    //   this.header1 += "(";
    // }
    // if (acronym != undefined && acronym != "") {
    //   this.header1 += acronym + " - ";
    // }
    // if (code != undefined && code != "") {
    //   this.header1 += code;
    // }
    // if ((title != undefined && title != "") &&
    //   ((acronym != undefined && acronym != "") ||
    //     (code != undefined && code != ""))) {
    //   this.header1 += ")";
    // }

    this.header1 = "<div style=\"font-size:12px;\"><span>Project</span>";

    if(this.projectInfo.startDate || this.projectInfo.endDate) {
      this.header1 += "<span> . "
    }
    if(this.projectInfo.startDate && !this.projectInfo.endDate) {
      this.header1 += "from ";
    }
    if(!this.projectInfo.startDate && this.projectInfo.endDate) {
      this.header1 += "until ";
    }
    if(this.projectInfo.startDate) {
      let startYear = (new Date(this.projectInfo.startDate)).getFullYear();
      this.header1 += startYear;
    }
    if(this.projectInfo.startDate && this.projectInfo.endDate) {
      this.header1 += " - ";
    }
    if(this.projectInfo.endDate) {
      let endYear = (new Date(this.projectInfo.endDate)).getFullYear();
      this.header1 += endYear;
    }
    if(this.projectInfo.startDate || this.projectInfo.endDate) {
      this.header1 += "</span>"
    }

    if(this.projectInfo.status) {
      this.header1 += "<span> . "+this.projectInfo.status+"</span>";
    }

    if(this.projectInfo.funding && this.projectInfo.funding.code) {
      this.header1 += "<span> . "+this.projectInfo.funding.code+"</span>";
    }
    this.header1 += "</div>";

    this.header1 += "<h1 style=\"margin:0;\"><div><a href=\""+window.location.href +"\">";
    if(this.projectInfo.acronym) {
      this.header1 += this.projectInfo.acronym;
    } else {
      this.header1 += "[no title available]";
    }
    this.header1 += "</a></div></h2>";
    //<showTitle [titleName]="title" classNames="uk-margin-remove-bottom"></showTitle>
    if(this.projectInfo.title) {
      this.header1 += "<div><span>"+this.projectInfo.title+"</span></div>";
    }
  }

  public download(url, filename) {
    //var url = window.URL.createObjectURL(new Blob([this.htmlResultDownload], { type: 'text/html' }));
    var a = window.document.createElement('a');
    window.document.body.appendChild(a);
    a.setAttribute('style', 'display: none');
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove(); // remove the element
  }


  public onSelectActiveTab(activeTabId) {
    if(this.activeTab != activeTabId) {   // tab really changed
      if (activeTabId == 'summary') {
        this.activeTab = 'summary';
      } else if (activeTabId == 'publications') {
        this.activeTab = 'publications';
        this.searchPublications(1, this.searchNumber);
      } else if (activeTabId == 'datasets') {
        this.activeTab = 'datasets';
        this.searchDatasets(1, this.searchNumber);
      } else if (activeTabId == 'software') {
        this.activeTab = 'software';
        this.searchSoftware(1, this.searchNumber);
      } else if (activeTabId == 'other') {
        this.activeTab = "other";
        this.searchOrps(1, this.searchNumber);
      } else if (activeTabId == 'statistics') {
        this.activeTab = 'statistics';
        setTimeout( () => {
          this.statsClicked = true;
          // this.cdr.detectChanges();
        });
      } else if (activeTabId == 'dmps') {
        this.activeTab = 'dmps';
        this.searchDmps(1, this.searchNumber);
      }
    }
  }

  private updateDescription(description: string) {
    // this._meta.updateTag({content: description.substring(0, 160)}, "name='description'");
    // this._meta.updateTag({content: description.substring(0, 160)}, "property='og:description'");
    this._meta.updateTag({content: description}, "name='description'");
    this._meta.updateTag({content: description}, "property='og:description'");
  }

  private updateTitle(title: string) {
    var _prefix = "";
    // if(!this.communityId) {
    //   _prefix = "OpenAIRE | ";
    // }
    // var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
    this._title.setTitle(title);
    this._meta.updateTag({content: title}, "property='og:title'");
  }

  private updateUrl(url: string) {
    this._meta.updateTag({content: url}, "property='og:url'");
  }

  private openLoading() {
    this.closeDownloadReportModal();

    if (this.loading) {
      this.loading.open();
    }
  }

  private closeLoading() {
    setTimeout(() => {
      if (this.loading) {
        this.loading.close();
      }
    }, 300)
  }

  private setMessageLoading(message: string) {
    if (this.loading) {
      this.loading.message = message;
    }
  }

  public confirmOpenFileDownloadError(fileType: string) {
    this.alertCsvError.cancelButton = false;
    this.alertCsvError.okButton = true;
    this.alertCsvError.alertTitle = "ERROR DOWNLOADING "+fileType+" FILE";
    this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
    this.alertCsvError.okButtonText = "OK";
    this.alertCsvError.open();
  }

  private handleError(message: string, error) {
    console.error("Project Landing Page: " + message, error);
  }

  isRouteAvailable(routeToCheck: string) {
    for (let i = 0; i < this._router.config.length; i++) {
      let routePath: string = this._router.config[i].path;
      if (routePath == routeToCheck) {
        return true;
      }
    }
    return false;
  }

  public getResultPreview(result: SearchResult, type: string): ResultPreview {
    return ResultPreview.searchResultConvert(result, type);
  }

  public scroll() {
    HelperFunctions.scroll();
  }

  public getParamsForSearchLink(type: string = null, subtype: string = null) {
    if(type) {
      if(subtype) {
        return this.routerHelper.createQueryParams(['f0', 'fv0', 'type', 'instancetypename', 'qf', 'sortBy'], ['relprojectid', this.projectId, type, subtype, 'false', 'resultdateofacceptance,descending']);
      } else {
        return this.routerHelper.createQueryParams(['f0', 'fv0', 'type', 'qf', 'sortBy'], ['relprojectid', this.projectId, type, 'false', 'resultdateofacceptance,descending']);
      }
    } else {
      return this.routerHelper.createQueryParams(['f0', 'fv0'], ['relprojectid', this.projectId]);
    }
  }

  public get hasPrimaryInfo(): boolean {
    return !!this.projectInfo && (!!this.projectInfo.description && this.projectInfo.description.length > 0);
  }

  public get hasSecondaryInfo(): boolean {
    return !!this.projectInfo && (
      (!!this.projectInfo.organizations && this.projectInfo.organizations.length > 0)
    );
  }

  // public get numberOfTabs(): number {
  //   if(this.tabsAreInitialized) {
  //     return this._numberOfTabs;
  //   }
  //
  //   if(!this.projectInfo
  //     || this.fetchPublications.searchUtils.status == this.errorCodes.LOADING
  //     || this.fetchDatasets.searchUtils.status == this.errorCodes.LOADING
  //     || this.fetchSoftware.searchUtils.status == this.errorCodes.LOADING
  //     || this.fetchOrps.searchUtils.status == this.errorCodes.LOADING) {
  //     return 0;
  //   }
  //
  //   if (this.hasPrimaryInfo || this.hasSecondaryInfo) {
  //     this.firstTab = "summary";
  //     this._numberOfTabs++;
  //   }
  //   if(this.fetchPublications.searchUtils.totalResults > 0 || this.fetchDatasets.searchUtils.totalResults > 0
  //     || this.fetchSoftware.searchUtils.totalResults > 0 || this.fetchOrps.searchUtils.totalResults > 0) {
  //     if(this.fetchPublications.searchUtils.totalResults > 0) {
  //       if(this._numberOfTabs == 0) {
  //         this.firstTab = 'publications';
  //         this.searchPublicationsInit();
  //       }
  //       this._numberOfTabs++;
  //     }
  //     if(this.fetchDatasets.searchUtils.totalResults > 0) {
  //       if(this._numberOfTabs == 0) {
  //         this.firstTab = 'datasets';
  //         this.searchDatasetsInit();
  //       }
  //       this._numberOfTabs++;
  //     }
  //     if(this.fetchSoftware.searchUtils.totalResults > 0) {
  //       if(this._numberOfTabs == 0) {
  //         this.firstTab = 'software';
  //         this.searchSoftwareInit();
  //       }
  //       this._numberOfTabs++;
  //     }
  //     if(this.fetchOrps.searchUtils.totalResults > 0) {
  //       if(this._numberOfTabs == 0) {
  //         this.firstTab = 'other';
  //         this.searchOrpsInit();
  //       }
  //       this._numberOfTabs++;
  //     }
  //     this._numberOfTabs++;
  //   }
  //   this.activeTab = this.firstTab;
  //   this.tabsAreInitialized = true;
  //   return this._numberOfTabs;
  // }

  public buildResultTypesForDownloading() {
    this.resultTypesForDownloading = [
      {label: "All "+OpenaireEntities.RESULTS, value: "results", disabled:
          (!this.projectInfo.funding ||
            (this.fetchPublications.searchUtils.totalResults == 0 &&
            this.fetchDatasets.searchUtils.totalResults == 0 &&
            this.fetchSoftware.searchUtils.totalResults == 0 &&
            this.fetchOrps.searchUtils.totalResults == 0))},
      {label: OpenaireEntities.PUBLICATIONS, value: "publications", disabled:
          (!this.projectInfo.funding || this.fetchPublications.searchUtils.totalResults == 0
            || this.fetchPublications.searchUtils.status != this.errorCodes.DONE)},
      {label: OpenaireEntities.DATASETS, value: "datasets", disabled:
          (!this.projectInfo.funding || this.fetchDatasets.searchUtils.totalResults == 0
            || this.fetchDatasets.searchUtils.status != this.errorCodes.DONE)},
      {label: OpenaireEntities.SOFTWARE, value: "software", disabled:
          (!this.projectInfo.funding || this.fetchSoftware.searchUtils.totalResults == 0
            || this.fetchSoftware.searchUtils.status != this.errorCodes.DONE)},
      {label: OpenaireEntities.OTHER, value: "other", disabled:
          (!this.projectInfo.funding || this.fetchOrps.searchUtils.totalResults == 0
            || this.fetchOrps.searchUtils.status != this.errorCodes.DONE)}
    ];
  }

	public viewAllDescriptionClicked() {
    if(this.isMobile) {
      this.summaryFsModal.title += " - Description";
      this.summaryFsModal.back = true;
      this.viewAllMobile = "description";
    } else {
      this.openDescriptionModal();
    }
  }

	public openDescriptionModal() {
		this.descriptionModal.alertFooter = false;
		this.descriptionModal.alertTitle = "Description";
		this.descriptionModal.open();
	}

	public clickedUsageMetrics() {
		setTimeout( () => {
      this.metricsClicked = true;
    });
	}

	public formatNumber(num: number | string) {
    let formatted = NumberUtils.roundNumber(+num);
    return formatted.number + formatted.size;
  }

	public cancelSummaryClicked() {
    this.summaryFsModal.title = "Summary";
    this.summaryFsModal.back = false;
    this.lessBtnOrganizations = false;
    this.viewAllMobile = "";
  }

	public openFsModal(fsModal: FullScreenModalComponent, title: string) {
    fsModal.title = title;
    fsModal.okButton = false;
    fsModal.stayOpenInBack = true;
    fsModal.open();
    this.tabMobile = title;
  }

	public getMetricsTooltip(value: string) {
		if (value == 'downloads') {
			return "<div class='uk-flex uk-flex-middle'><a href='https://usagecounts.openaire.eu/' target='_blank'><img src='assets/common-assets/logo-small-usage-counts.png' loading='lazy' alt='OpenAIRE UsageCounts'></a><span class='uk-text-uppercase uk-margin-small-left'>Downloads provided by <a href='https://usagecounts.openaire.eu/' target='_blank' class='uk-link-reset'><strong>UsageCounts</strong></a></div>";
		} else if (value == 'views') {
			return "<div class='uk-flex uk-flex-middle'><a href='https://usagecounts.openaire.eu/' target='_blank'><img class='uk-margin-small-right' src='assets/common-assets/logo-small-usage-counts.png' loading='lazy' alt='OpenAIRE UsageCounts'></a><span class='uk-text-uppercase uk-margin-small-left'>Views provided by <a href='https://usagecounts.openaire.eu/' target='_blank' class='uk-link-reset'><strong>UsageCounts</strong></a></div>";
		}
	}

  public addEoscPrevInParams(obj) {
    if(properties.adminToolsPortalType == "eosc" && this.prevPath) {
      let splitted: string[] = this.prevPath.split("?");
      obj = this.routerHelper.addQueryParam("return_path", splitted[0], obj);
      if(splitted.length > 0) {
        obj = this.routerHelper.addQueryParam("search_params", splitted[1], obj);
      }
    }
    return obj;
  }

  public get eoscBackLink() {
    if(this.prevPath && this.referrer && ((this.referrer == "https://eosc-search-service.grid.cyfronet.pl/") || (this.referrer == "https://beta.search.marketplace.eosc-portal.eu/") || (this.referrer == "https://search.marketplace.eosc-portal.eu/"))) {
      return this.referrer+this.prevPath;
    } else {
      return "https://"+(this.properties.environment == "beta" ? "beta." : "")+"search.marketplace.eosc-portal.eu/";
    }
  }
}
